|
| 1 | +# Copyright 2017 The Kubernetes Authors. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# Simple example to show loading config from the cluster |
| 16 | + |
| 17 | +# |
| 18 | +# If you get 403 errors from API server you will have to configure |
| 19 | +# RBAC to add necessay permissions. |
| 20 | +# |
| 21 | +# --- |
| 22 | +# kind: ClusterRole |
| 23 | +# apiVersion: rbac.authorization.k8s.io/v1 |
| 24 | +# metadata: |
| 25 | +# name: pods-list |
| 26 | +# rules: |
| 27 | +# - apiGroups: [""] |
| 28 | +# resources: ["pods"] |
| 29 | +# verbs: ["list"] |
| 30 | +# --- |
| 31 | +# kind: ClusterRoleBinding |
| 32 | +# apiVersion: rbac.authorization.k8s.io/v1 |
| 33 | +# metadata: |
| 34 | +# name: pods-list |
| 35 | +# subjects: |
| 36 | +# - kind: ServiceAccount |
| 37 | +# name: default |
| 38 | +# namespace: default |
| 39 | +# roleRef: |
| 40 | +# kind: ClusterRole |
| 41 | +# name: pods-list |
| 42 | +# apiGroup: rbac.authorization.k8s.io |
| 43 | +# --- |
| 44 | +# |
| 45 | +# Doc: https://kubernetes.io/docs/reference/access-authn-authz/rbac/ |
| 46 | +# |
| 47 | +# This example can be run from the image: https://hub.docker.com/r/tpimages/kubernetes_asyncio_examples/ |
| 48 | +# |
| 49 | +# $ kubectl run kubernetes-asyncio-examples --image tpimages/kubernetes_asyncio_examples |
| 50 | +# |
| 51 | + |
| 52 | +import asyncio |
| 53 | +import sys |
| 54 | +import traceback |
| 55 | + |
| 56 | +from kubernetes_asyncio import client, config |
| 57 | + |
| 58 | + |
| 59 | +async def main(): |
| 60 | + |
| 61 | + while True: |
| 62 | + |
| 63 | + try: |
| 64 | + |
| 65 | + # it works only if this script is run by K8s as a POD |
| 66 | + config.load_incluster_config() |
| 67 | + |
| 68 | + v1 = client.CoreV1Api() |
| 69 | + print("Listing pods with their IPs:") |
| 70 | + ret = await v1.list_pod_for_all_namespaces() |
| 71 | + |
| 72 | + for i in ret.items: |
| 73 | + print(i.status.pod_ip, i.metadata.namespace, i.metadata.name) |
| 74 | + |
| 75 | + except Exception: |
| 76 | + traceback.print_exc(file=sys.stdout) |
| 77 | + |
| 78 | + finally: |
| 79 | + print("sleep 10s") |
| 80 | + await asyncio.sleep(10) |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + loop = asyncio.get_event_loop() |
| 85 | + loop.run_until_complete(main()) |
| 86 | + loop.close() |
0 commit comments