Automating Kubernetes Tasks with the Python Client Library
This tutorial demonstrates how to set up a local KinD cluster, configure authentication, use raw curl commands, and employ the official Kubernetes Python client to list pods, create deployments, watch events, and manage RBAC, providing a complete guide for automating Kubernetes operations with Python.
Kubernetes has become the de‑facto standard for container orchestration, and many repetitive tasks can be automated using the official Python client library instead of ad‑hoc shell scripts.
Prerequisites : Create a local KinD cluster using the provided # kind.yaml apiVersion: kind.x-k8s.io/v1alpha4 kind: Cluster name: api-playground nodes: - role: control-plane - role: worker - role: worker - role: worker configuration and start it with kind create cluster --image kindest/node:v1.23.5 --config=kind.yaml . Verify the cluster with kubectl cluster-info --context kind-api-playground and kubectl get nodes .
Install the Python client in a virtual environment: python3 -m venv venv source venv/bin/activate pip install kubernetes .
Authentication : Create a long‑lived ServiceAccount token to avoid repeated logins. Use kubectl create sa playground and extract the token with export KIND_TOKEN=$(kubectl get secret playground-token-v8bq7 -o json | jq -r .data.token | base64 --decode) . Bind a ClusterRole to the ServiceAccount so it can manage pods: kubectl create clusterrole manage-pods --verb=get --verb=list --verb=watch --verb=create --verb=update --verb=patch --verb=delete --resource=pods kubectl -n default create rolebinding sa-manage-pods --clusterrole=manage-pods --serviceaccount=default:playground . For full admin rights in KinD you can also run kubectl create clusterrolebinding sa-cluster-admin --clusterrole=cluster-admin --serviceaccount=default:playground .
Raw HTTP requests : By running kubectl get pods -v 10 you can see the underlying curl command. Re‑use the token in a manual curl request to list pods or create resources, e.g. curl -k -XGET -H "Authorization: Bearer $KIND_TOKEN" https://127.0.0.1:36599/api/v1/namespaces/default/pods . This approach is useful when a kubectl sub‑command does not exist or when working with other distributions such as OpenShift.
Python client usage : Configure the client with the token and host: from kubernetes import client import os configuration = client.Configuration() configuration.api_key_prefix["authorization"] = "Bearer" configuration.host = "https://127.0.0.1:36599" configuration.api_key["authorization"] = os.getenv("KIND_TOKEN") configuration.verify_ssl = False # only for KinD testing api_client = client.ApiClient(configuration) v1 = client.CoreV1Api(api_client) List pods in the default namespace and print their name, namespace, and IP. Create a Deployment using a Python dict manifest and wait until three replicas become available, handling ApiException if the status check fails. Watch the first ten events in the default namespace with the watch API: from kubernetes import client, watch v1 = client.CoreV1Api(api_client) count = 10 w = watch.Watch() for event in w.stream(partial(v1.list_namespaced_event, namespace="default"), timeout_seconds=10): print(f"Event - Message: {event['object']['message']} at {event['object']['metadata']['creationTimestamp']}") count -= 1 if not count: w.stop() print("Finished namespace stream.")
The tutorial also shows how to use the generated model classes (e.g., client.V1Deployment , client.V1ObjectMeta , client.V1PodSpec ) for a more object‑oriented definition of resources, emphasizing the need to consult the model documentation for correct field types.
Overall, the guide provides a step‑by‑step walkthrough for automating Kubernetes operations with Python, covering cluster setup, authentication, raw API calls, client configuration, CRUD operations, role management, and event watching.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.