884: Cleanup examples folder
This commit is contained in:
parent
91c080d390
commit
04c499c395
@ -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).
|
||||
|
||||
17
examples/README.md
Normal file
17
examples/README.md
Normal file
@ -0,0 +1,17 @@
|
||||
# Python Client Examples
|
||||
|
||||
This directory contains various examples how to use the Python client. Please
|
||||
read the description at the top of each script for more information about what
|
||||
it does and any prequisite steps. 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 via 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).
|
||||
@ -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
|
||||
|
||||
@ -12,6 +12,11 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Reads the list of the available API versions and prints them.
|
||||
Similar to running `kubectl api-versions`.
|
||||
"""
|
||||
|
||||
from kubernetes import client, config
|
||||
|
||||
|
||||
@ -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 @@ from kubernetes import client, config
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
config.load_kube_config()
|
||||
|
||||
api = client.CustomObjectsApi()
|
||||
|
||||
@ -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
|
||||
@ -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()
|
||||
@ -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/
|
||||
"""
|
||||
Showcases loading the Kubernetes config from within the 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 the 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()
|
||||
|
||||
@ -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 within 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="/",
|
||||
@ -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",
|
||||
@ -12,39 +12,41 @@
|
||||
# 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.")
|
||||
return
|
||||
contexts = [context['name'] for context in contexts]
|
||||
active_index = contexts.index(active_context['name'])
|
||||
cluster1, first_index = pick(contexts, title="Pick the first context",
|
||||
default_index=active_index)
|
||||
cluster2, _ = pick(contexts, title="Pick the second context",
|
||||
default_index=first_index)
|
||||
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)
|
||||
|
||||
client1 = client.CoreV1Api(
|
||||
api_client=config.new_client_from_config(context=cluster1))
|
||||
client2 = client.CoreV1Api(
|
||||
api_client=config.new_client_from_config(context=cluster2))
|
||||
print("Active host is %s" % configuration.Configuration().host)
|
||||
|
||||
print("\nList of pods on %s:" % cluster1)
|
||||
for i in client1.list_pod_for_all_namespaces().items:
|
||||
print("%s\t%s\t%s" %
|
||||
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
|
||||
|
||||
print("\n\nList of pods on %s:" % cluster2)
|
||||
for i in client2.list_pod_for_all_namespaces().items:
|
||||
print("%s\t%s\t%s" %
|
||||
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
|
||||
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__':
|
||||
|
||||
@ -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()
|
||||
@ -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
|
||||
}
|
||||
|
||||
@ -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
|
||||
}
|
||||
@ -12,6 +12,10 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""
|
||||
Showcases loading the Kubernetes config from outside of the cluster.
|
||||
"""
|
||||
|
||||
from kubernetes import client, config
|
||||
|
||||
|
||||
@ -11,5 +11,3 @@ spec:
|
||||
command: ["perl", "-Mbignum=bpi", "-wle", "print bpi(2000)"]
|
||||
restartPolicy: Never
|
||||
backoffLimit: 4
|
||||
|
||||
|
||||
|
||||
@ -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():
|
||||
54
examples/pod_config_list.py
Normal file
54
examples/pod_config_list.py
Normal file
@ -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()
|
||||
129
examples/pod_exec.py
Normal file
129
examples/pod_exec.py
Normal file
@ -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.
|
||||
|
||||
"""
|
||||
Showcases 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()
|
||||
@ -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 waiting for 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__':
|
||||
@ -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 = "<token>"
|
||||
|
||||
# Create a configuration object
|
||||
aConfiguration = client.Configuration()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user