diff --git a/README.md b/README.md index 732941f098..99f2a8ddd4 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ More examples can be found in [examples](examples/) folder. To run examples, run python -m examples.example1 ``` -(replace example1 with the example base filename) +(replace example1 with one of the filenames in the examples folder) ## Documentation @@ -178,4 +178,4 @@ Specifically check `ipaddress` and `urllib3` package versions to make sure they Starting from 4.0 release, we do not support directly calling exec or attach calls. you should use stream module to call them. so instead of `resp = api.connect_get_namespaced_pod_exec(name, ...` you should call `resp = stream(api.connect_get_namespaced_pod_exec, name, ...`. -See more at [exec example](examples/exec.py). +See more at [exec example](examples/pod_exec.py). diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000000..0c4d513e8d --- /dev/null +++ b/examples/README.md @@ -0,0 +1,17 @@ +# Python Client Examples + +This directory contains various examples of how to use the Python client. +Please read the description at the top of each example for more information +about what the script does and any prequisites. Most scripts also include +comments throughout the code. + +## Setup + +These scripts require Python 2.7 or 3.5+ and the Kubernetes client which can be +installed following the directions +[here](https://github.com/kubernetes-client/python#installation). + +## Contributions + +If you find a problem please file an +[issue](https://github.com/kubernetes-client/python/issues). diff --git a/examples/__init__.py b/examples/__init__.py index 13d0123d14..a010399d95 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Empty init file to make examples folder a python module. +# Empty init file to make examples folder a python module diff --git a/examples/example3.py b/examples/api_discovery.py similarity index 92% rename from examples/example3.py rename to examples/api_discovery.py index 2ee3685b58..9c91fe429c 100644 --- a/examples/example3.py +++ b/examples/api_discovery.py @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Reads the list of available API versions and prints them. Similar to running +`kubectl api-versions`. +""" + from kubernetes import client, config diff --git a/examples/custom_object.py b/examples/custom_object.py index 87524c006a..0c2b36aefb 100644 --- a/examples/custom_object.py +++ b/examples/custom_object.py @@ -12,29 +12,31 @@ # See the License for the specific language governing permissions and # limitations under the License. -# This example use an example CRD from this tutorial: -# https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ -# -# The following yaml manifest has to be applied first: -# -# apiVersion: apiextensions.k8s.io/v1beta1 -# kind: CustomResourceDefinition -# metadata: -# name: crontabs.stable.example.com -# spec: -# group: stable.example.com -# versions: -# - name: v1 -# served: true -# storage: true -# scope: Namespaced -# names: -# plural: crontabs -# singular: crontab -# kind: CronTab -# shortNames: -# - ct +""" +Uses a Custom Resource Definition (CRD) to create a custom object, in this case +a CronTab. This example use an example CRD from this tutorial: +https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/ +The following yaml manifest has to be applied first: + +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: crontabs.stable.example.com +spec: + group: stable.example.com + versions: + - name: v1 + served: true + storage: true + scope: Namespaced + names: + plural: crontabs + singular: crontab + kind: CronTab + shortNames: + - ct +""" from pprint import pprint @@ -42,7 +44,6 @@ def main(): - config.load_kube_config() api = client.CustomObjectsApi() diff --git a/examples/create_deployment.py b/examples/deployment_create.py similarity index 100% rename from examples/create_deployment.py rename to examples/deployment_create.py diff --git a/examples/deployment_examples.py b/examples/deployment_crud.py similarity index 97% rename from examples/deployment_examples.py rename to examples/deployment_crud.py index 9d354f7d3d..a25bb518aa 100644 --- a/examples/deployment_examples.py +++ b/examples/deployment_crud.py @@ -13,8 +13,7 @@ # limitations under the License. """ -This example shows how to work with AppsV1Api to create, modify and delete -deployments +Creates, updates, and deletes a deployment using AppsV1Api. """ from kubernetes import client, config diff --git a/examples/exec.py b/examples/exec.py deleted file mode 100644 index d1f9e9e301..0000000000 --- a/examples/exec.py +++ /dev/null @@ -1,97 +0,0 @@ -import time - -from kubernetes import config -from kubernetes.client import Configuration -from kubernetes.client.apis import core_v1_api -from kubernetes.client.rest import ApiException -from kubernetes.stream import stream - -config.load_kube_config() -c = Configuration() -c.assert_hostname = False -Configuration.set_default(c) -api = core_v1_api.CoreV1Api() -name = 'busybox-test' - -resp = None -try: - resp = api.read_namespaced_pod(name=name, - namespace='default') -except ApiException as e: - if e.status != 404: - print("Unknown error: %s" % e) - exit(1) - -if not resp: - print("Pod %s does not exist. Creating it..." % name) - pod_manifest = { - 'apiVersion': 'v1', - 'kind': 'Pod', - 'metadata': { - 'name': name - }, - 'spec': { - 'containers': [{ - 'image': 'busybox', - 'name': 'sleep', - "args": [ - "/bin/sh", - "-c", - "while true;do date;sleep 5; done" - ] - }] - } - } - resp = api.create_namespaced_pod(body=pod_manifest, - namespace='default') - while True: - resp = api.read_namespaced_pod(name=name, - namespace='default') - if resp.status.phase != 'Pending': - break - time.sleep(1) - print("Done.") - - -# calling exec and wait for response. -exec_command = [ - '/bin/sh', - '-c', - 'echo This message goes to stderr >&2; echo This message goes to stdout'] -resp = stream(api.connect_get_namespaced_pod_exec, name, 'default', - command=exec_command, - stderr=True, stdin=False, - stdout=True, tty=False) -print("Response: " + resp) - -# Calling exec interactively. -exec_command = ['/bin/sh'] -resp = stream(api.connect_get_namespaced_pod_exec, name, 'default', - command=exec_command, - stderr=True, stdin=True, - stdout=True, tty=False, - _preload_content=False) -commands = [ - "echo test1", - "echo \"This message goes to stderr\" >&2", -] -while resp.is_open(): - resp.update(timeout=1) - if resp.peek_stdout(): - print("STDOUT: %s" % resp.read_stdout()) - if resp.peek_stderr(): - print("STDERR: %s" % resp.read_stderr()) - if commands: - c = commands.pop(0) - print("Running command... %s\n" % c) - resp.write_stdin(c + "\n") - else: - break - -resp.write_stdin("date\n") -sdate = resp.readline_stdout(timeout=3) -print("Server date command returns: %s" % sdate) -resp.write_stdin("whoami\n") -user = resp.readline_stdout(timeout=3) -print("Server user is: %s" % user) -resp.close() diff --git a/examples/in_cluster_config.py b/examples/in_cluster_config.py index 86b8704e2c..55f9eb792e 100644 --- a/examples/in_cluster_config.py +++ b/examples/in_cluster_config.py @@ -12,47 +12,46 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Simple example to show loading config from the cluster -# -# It works only from a pod. You can start an image with Python -# (for example python:latest), exec into the pod, install the library, -# then try out this example. -# -# If you get 403 errors from API server you will have to configure -# RBAC to add the permission to list pods. -# -# --- -# kind: ClusterRole -# apiVersion: rbac.authorization.k8s.io/v1 -# metadata: -# name: pods-list -# rules: -# - apiGroups: [""] -# resources: ["pods"] -# verbs: ["list"] -# --- -# kind: ClusterRoleBinding -# apiVersion: rbac.authorization.k8s.io/v1 -# metadata: -# name: pods-list -# subjects: -# - kind: ServiceAccount -# name: default -# namespace: default -# roleRef: -# kind: ClusterRole -# name: pods-list -# apiGroup: rbac.authorization.k8s.io -# --- -# -# Doc: https://kubernetes.io/docs/reference/access-authn-authz/rbac/ +""" +Shows how to load a Kubernetes config from within a cluster. This script +must be run within a pod. You can start a pod with a Python image (for +example, `python:latest`), exec into the pod, install the library, then run +this example. + +If you get 403 errors from the API server you will have to configure RBAC to +add permission to list pods by applying the following manifest: + +--- +kind: ClusterRole +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: pods-list +rules: +- apiGroups: [""] + resources: ["pods"] + verbs: ["list"] + +--- +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: pods-list +subjects: +- kind: ServiceAccount + name: default + namespace: default +roleRef: + kind: ClusterRole + name: pods-list + apiGroup: rbac.authorization.k8s.io + +Documentation: https://kubernetes.io/docs/reference/access-authn-authz/rbac/ +""" from kubernetes import client, config def main(): - - # it works only if this script is run by K8s as a POD config.load_incluster_config() v1 = client.CoreV1Api() diff --git a/examples/ingress-example.py b/examples/ingress_create.py similarity index 95% rename from examples/ingress-example.py rename to examples/ingress_create.py index 35b9385cb4..fa5739c8f5 100644 --- a/examples/ingress-example.py +++ b/examples/ingress_create.py @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Creates deployment, service, and ingress objects. The ingress allows external +network access to the cluster. +""" + from kubernetes import client, config @@ -73,7 +78,7 @@ def create_ingress(networking_v1_beta1_api): }), spec=client.NetworkingV1beta1IngressSpec( rules=[client.NetworkingV1beta1IngressRule( - host="boddulabs.com", + host="example.com", http=client.NetworkingV1beta1HTTPIngressRuleValue( paths=[client.NetworkingV1beta1HTTPIngressPath( path="/", diff --git a/examples/job_examples.py b/examples/job_crud.py similarity index 98% rename from examples/job_examples.py rename to examples/job_crud.py index 39a71b8921..b18b152d4d 100644 --- a/examples/job_examples.py +++ b/examples/job_crud.py @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Creates, updates, and deletes a job object. +""" + from os import path import yaml @@ -46,7 +50,6 @@ def create_job_object(): def create_job(api_instance, job): - # Create job api_response = api_instance.create_namespaced_job( body=job, namespace="default") @@ -56,7 +59,6 @@ def create_job(api_instance, job): def update_job(api_instance, job): # Update container image job.spec.template.spec.containers[0].image = "perl" - # Update the job api_response = api_instance.patch_namespaced_job( name=JOB_NAME, namespace="default", @@ -65,7 +67,6 @@ def update_job(api_instance, job): def delete_job(api_instance): - # Delete job api_response = api_instance.delete_namespaced_job( name=JOB_NAME, namespace="default", diff --git a/examples/multiple_clusters.py b/examples/multiple_clusters.py index 68a5d2ff8c..94b0458cd8 100644 --- a/examples/multiple_clusters.py +++ b/examples/multiple_clusters.py @@ -12,14 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Allows you to pick a context and then lists all pods in the chosen context. + +Please install the pick library before running this example. +""" + from kubernetes import client, config -# install pick using "pip install pick". It is not included -# as a dependency because it only used in examples -from pick import pick +from kubernetes.client import configuration +from pick import pick # install pick using `pip install pick` def main(): - contexts, active_context = config.list_kube_config_contexts() if not contexts: print("Cannot find any context in kube-config file.") diff --git a/examples/manage_node_labels.py b/examples/node_labels.py similarity index 82% rename from examples/manage_node_labels.py rename to examples/node_labels.py index e350ad372d..22ac3197ad 100644 --- a/examples/manage_node_labels.py +++ b/examples/node_labels.py @@ -12,19 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Changes the labels of the "minikube" node. Adds the label "foo" with value +"bar" and will overwrite the "foo" label if it already exists. Removes the +label "baz". +""" + from pprint import pprint from kubernetes import client, config def main(): - """ - Change labels of the "minikube" node: - - Add label "foo" with value "bar". This will overwrite the "foo" label - if it already exists. - - Remove the label "baz" from the node. - """ - config.load_kube_config() api_instance = client.CoreV1Api() diff --git a/examples/notebooks/test.ipynb b/examples/notebooks/test.ipynb deleted file mode 100644 index 9f7aa6b830..0000000000 --- a/examples/notebooks/test.ipynb +++ /dev/null @@ -1,104 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "from kubernetes import client, config" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "config.load_incluster_config()" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "v1=client.CoreV1Api()" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "default\n", - "kube-system\n", - "kubeless\n" - ] - } - ], - "source": [ - "for ns in v1.list_namespace().items:\n", - " print ns.metadata.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 2", - "language": "python", - "name": "python2" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 2 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.12" - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} - diff --git a/examples/notebooks/watch_notebook.ipynb b/examples/notebooks/watch_notebook.ipynb deleted file mode 100644 index e7ec43c67d..0000000000 --- a/examples/notebooks/watch_notebook.ipynb +++ /dev/null @@ -1,129 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "How to watch changes to an object\n", - "==================\n", - "\n", - "In this notebook, we learn how kubernetes API resource Watch endpoint is used to observe resource changes. It can be used to get information about changes to any kubernetes object." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [ - "from kubernetes import client, config, watch" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Load config from default location." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "config.load_kube_config()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "### Create API instance" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [ - "api_instance = client.CoreV1Api()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "deletable": true, - "editable": true - }, - "source": [ - "### Run a Watch on the Pods endpoint. \n", - "Watch would be executed and produce output about changes to any Pod. After running the cell below, You can test this by running the Pod notebook [create_pod.ipynb](create_pod.ipynb) and observing the additional output here. You can stop the cell from running by restarting the kernel." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [ - "w = watch.Watch()\n", - "for event in w.stream(api_instance.list_pod_for_all_namespaces):\n", - " print(\"Event: %s %s %s\" % (event['type'],event['object'].kind, event['object'].metadata.name))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "deletable": true, - "editable": true - }, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 2", - "language": "python", - "name": "python2" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 2 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.6" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/example1.py b/examples/out_of_cluster_config.py similarity index 93% rename from examples/example1.py rename to examples/out_of_cluster_config.py index 214fd190f7..f391be236d 100644 --- a/examples/example1.py +++ b/examples/out_of_cluster_config.py @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Shows how to load a Kubernetes config from outside of the cluster. +""" + from kubernetes import client, config diff --git a/examples/pi-job.yaml b/examples/pi-job.yaml index dc736f2da9..ee1d89fdd8 100644 --- a/examples/pi-job.yaml +++ b/examples/pi-job.yaml @@ -11,5 +11,3 @@ spec: command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"] restartPolicy: Never backoffLimit: 4 - - diff --git a/examples/example4.py b/examples/pick_kube_config_context.py similarity index 88% rename from examples/example4.py rename to examples/pick_kube_config_context.py index 334e282c2f..962639669b 100644 --- a/examples/example4.py +++ b/examples/pick_kube_config_context.py @@ -12,11 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Allows you to pick a context and then lists all pods in the chosen context. + +Please install the pick library before running this example. +""" + from kubernetes import client, config from kubernetes.client import configuration -# install pick using "pip install pick". It is not included -# as a dependency because it only used in examples -from pick import pick +from pick import pick # install pick using `pip install pick` def main(): diff --git a/examples/pod_config_list.py b/examples/pod_config_list.py new file mode 100644 index 0000000000..09bbde9b69 --- /dev/null +++ b/examples/pod_config_list.py @@ -0,0 +1,54 @@ +# Copyright 2016 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Allows you to pick a context and then lists all pods in the chosen context. A +context includes a cluster, a user, and a namespace. + +Please install the pick library before running this example. +""" + +from kubernetes import client, config +from kubernetes.client import configuration +from pick import pick # install pick using `pip install pick` + + +def main(): + contexts, active_context = config.list_kube_config_contexts() + if not contexts: + print("Cannot find any context in kube-config file.") + return + contexts = [context['name'] for context in contexts] + active_index = contexts.index(active_context['name']) + option, _ = pick(contexts, title="Pick the context to load", + default_index=active_index) + # Configs can be set in Configuration class directly or using helper + # utility + config.load_kube_config(context=option) + + print("Active host is %s" % configuration.Configuration().host) + + v1 = client.CoreV1Api() + print("Listing pods with their IPs:") + ret = v1.list_pod_for_all_namespaces(watch=False) + for item in ret.items: + print( + "%s\t%s\t%s" % + (item.status.pod_ip, + item.metadata.namespace, + item.metadata.name)) + + +if __name__ == '__main__': + main() diff --git a/examples/pod_exec.py b/examples/pod_exec.py new file mode 100644 index 0000000000..98b717f4a6 --- /dev/null +++ b/examples/pod_exec.py @@ -0,0 +1,129 @@ +# Copyright 2019 The Kubernetes Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Shows the functionality of exec using a Busybox container. +""" + +import time + +from kubernetes import config +from kubernetes.client import Configuration +from kubernetes.client.apis import core_v1_api +from kubernetes.client.rest import ApiException +from kubernetes.stream import stream + + +def exec_commands(api_instance): + name = 'busybox-test' + resp = None + try: + resp = api_instance.read_namespaced_pod(name=name, + namespace='default') + except ApiException as e: + if e.status != 404: + print("Unknown error: %s" % e) + exit(1) + + if not resp: + print("Pod %s does not exist. Creating it..." % name) + pod_manifest = { + 'apiVersion': 'v1', + 'kind': 'Pod', + 'metadata': { + 'name': name + }, + 'spec': { + 'containers': [{ + 'image': 'busybox', + 'name': 'sleep', + "args": [ + "/bin/sh", + "-c", + "while true;do date;sleep 5; done" + ] + }] + } + } + resp = api_instance.create_namespaced_pod(body=pod_manifest, + namespace='default') + while True: + resp = api_instance.read_namespaced_pod(name=name, + namespace='default') + if resp.status.phase != 'Pending': + break + time.sleep(1) + print("Done.") + + # Calling exec and waiting for response + exec_command = [ + '/bin/sh', + '-c', + 'echo This message goes to stderr; echo This message goes to stdout'] + resp = stream(api_instance.connect_get_namespaced_pod_exec, + name, + 'default', + command=exec_command, + stderr=True, stdin=False, + stdout=True, tty=False) + print("Response: " + resp) + + # Calling exec interactively + exec_command = ['/bin/sh'] + resp = stream(api_instance.connect_get_namespaced_pod_exec, + name, + 'default', + command=exec_command, + stderr=True, stdin=True, + stdout=True, tty=False, + _preload_content=False) + commands = [ + "echo This message goes to stdout", + "echo \"This message goes to stderr\" >&2", + ] + + while resp.is_open(): + resp.update(timeout=1) + if resp.peek_stdout(): + print("STDOUT: %s" % resp.read_stdout()) + if resp.peek_stderr(): + print("STDERR: %s" % resp.read_stderr()) + if commands: + c = commands.pop(0) + print("Running command... %s\n" % c) + resp.write_stdin(c + "\n") + else: + break + + resp.write_stdin("date\n") + sdate = resp.readline_stdout(timeout=3) + print("Server date command returns: %s" % sdate) + resp.write_stdin("whoami\n") + user = resp.readline_stdout(timeout=3) + print("Server user is: %s" % user) + resp.close() + + +def main(): + config.load_kube_config() + c = Configuration() + c.assert_hostname = False + Configuration.set_default(c) + core_v1 = core_v1_api.CoreV1Api() + + exec_commands(core_v1) + + +if __name__ == '__main__': + main() diff --git a/examples/example2.py b/examples/pod_namespace_watch.py similarity index 63% rename from examples/example2.py rename to examples/pod_namespace_watch.py index 003d5c9601..f09768cf7d 100644 --- a/examples/example2.py +++ b/examples/pod_namespace_watch.py @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Uses watch to print the stream of events from list namespaces and list pods. +The script will wait for 10 events related to namespaces to occur within +the `timeout_seconds` threshold and then move on to wait for another 10 events +related to pods to occur within the `timeout_seconds` threshold. +""" + from kubernetes import client, config, watch @@ -29,8 +36,18 @@ def main(): count -= 1 if not count: w.stop() + print("Finished namespace stream.") - print("Ended.") + for event in w.stream(v1.list_pod_for_all_namespaces, timeout_seconds=10): + print("Event: %s %s %s" % ( + event['type'], + event['object'].kind, + event['object'].metadata.name) + ) + count -= 1 + if not count: + w.stop() + print("Finished pod stream.") if __name__ == '__main__': diff --git a/examples/remote_cluster.py b/examples/remote_cluster.py index 8cf39efec5..b72b39b4e9 100644 --- a/examples/remote_cluster.py +++ b/examples/remote_cluster.py @@ -23,7 +23,7 @@ def main(): # Define the barer token we are going to use to authenticate. # See here to create the token: # https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/ - aToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + aToken = "" # Create a configuration object aConfiguration = client.Configuration()