Skip to content
Visual explainer 3h to learn 3 steps

Kubernetes Python client

Script cluster checks and clean-ups in Python.

By Invicly Tech, , in Full DevOps with Python. About 11 minutes to read.

Topic 30 of 34

In short

The official Kubernetes Python client talks to the same API as kubectl. It lets you script checks and clean-ups, like removing failed Pods, with real logic and a dry-run mode.

Explained simply

kubectl is great for typing commands, but some jobs need real logic: check every namespace, skip Pods with a certain label, keep a count, send a report. Shell scripts that parse kubectl output get messy fast. Python with the official kubernetes package is cleaner.

The Python client talks to the same API server as kubectl, using the same kubeconfig file and the same permissions. Anything kubectl can do, the client can do, and you get Python objects back instead of text to parse.

The basic pattern is always the same. Load the configuration, create an API object for the group of resources you need, call a method like list_namespaced_pod, then loop over the results and read fields like pod.status.phase.

Scripts that change things, like deleting Pods, should be safe by default. They print what they would do, and only act when you pass a flag such as --apply. The same script can later run inside the cluster as a scheduled job.

Press Play on a diagram to walk through it one step at a time.

FlowClean up failed Pods
  1. 1
    Load kubeconfig

    Same credentials and context kubectl uses.

  2. 2
    Create CoreV1Api

    Client for Pods, Services and namespaces.

  3. 3
    List Pods

    All namespaces, filtered by status.phase=Failed.

  4. 4
    Report in dry run

    Print namespace and name of each match.

  5. 5
    Delete with flag

    Only when --apply is passed.

Comparekubectl in a shell script vs the Python client
kubectl plus bash
  • Fast for one-liners
  • Parse text or jsonpath output
  • Error handling is hard
  • Needs kubectl in the image
Python client
  • Real objects and logic
  • Exceptions with HTTP status codes
  • Easy to unit test and reuse
  • Runs as a CronJob with a ServiceAccount

In depth

How the client is organized

The kubernetes package (pip install kubernetes) is generated from the API server's OpenAPI specification, so its classes mirror the API groups. Core objects such as Pods, Services, ConfigMaps, Secrets, Namespaces and Nodes are in CoreV1Api. Deployments and StatefulSets are in AppsV1Api, Jobs and CronJobs in BatchV1Api, and Ingresses in NetworkingV1Api.

Method names follow one pattern: verb, then namespaced or not, then kind. list_namespaced_pod lists Pods in one namespace, list_pod_for_all_namespaces lists them everywhere, and read_, create_, patch_, replace_ and delete_ do the rest. Results are model objects with snake_case attributes: the JSON field containerStatuses becomes pod.status.container_statuses. Call .to_dict() if you want plain dictionaries.

The client's major version follows the Kubernetes minor version: client 33.x was generated for Kubernetes 1.33. Pick a version close to your cluster's. For custom resources there is CustomObjectsApi, and the separate dynamic client can work with any resource type by name.

MapWhich API class holds which resources
kubernetes.client
  • CoreV1Api
    • Pods
    • Services
    • ConfigMaps, Secrets
    • Namespaces, Nodes
  • AppsV1Api
    • Deployments
    • StatefulSets
    • DaemonSets
  • BatchV1Api
    • Jobs
    • CronJobs
  • NetworkingV1Api
    • Ingresses
    • NetworkPolicies
  • CustomObjectsApi
    • Any custom resource

Loading config on a laptop and inside a Pod

On your machine, config.load_kube_config() reads ~/.kube/config (or the KUBECONFIG variable) and uses the current context. You can pass context="kind-dev" to choose a cluster explicitly, which is safer for scripts than trusting whatever context was used last. config.list_kube_config_contexts() returns all contexts and the active one, so a script can print which cluster it is about to touch.

Inside a Pod there is no kubeconfig. Kubernetes mounts a ServiceAccount token, the CA certificate and the namespace into /var/run/secrets/kubernetes.io/serviceaccount/, and sets the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT variables. config.load_incluster_config() uses those. It raises ConfigException when they are missing.

A common pattern tries in-cluster config first and falls back to the kubeconfig, so one script works in both places. For managed clusters like EKS, the kubeconfig user entry often runs a command (aws eks get-token) to fetch a short-lived token, and the Python client runs that command too.

FlowOne script, two places to run
  1. Step 1
    Try load_incluster_config

    Works when running in a Pod

  2. Step 2
    On ConfigException

    Not in a cluster

  3. Step 3
    load_kube_config

    Use the local kubeconfig and context

  4. Step 4
    Print the target

    Show cluster or context before acting

Reading Pod status correctly

pod.status.phase alone hides most problems. A Pod in CrashLoopBackOff usually has phase Running, because the Pod exists and its container keeps restarting. The useful details are in pod.status.container_statuses, a list with one entry per container. Each has ready (True or False), restart_count, and state, where exactly one of state.running, state.waiting or state.terminated is set. The waiting reason holds values like CrashLoopBackOff, ImagePullBackOff or CreateContainerConfigError. last_state.terminated holds the exit code and reason (such as OOMKilled) of the previous run.

container_statuses is None while a Pod is still Pending and not scheduled, so always guard with or [] before looping.

Phase Failed covers more than crashes. Pods evicted by the kubelet because the node ran low on memory or disk stay around with phase Failed and status.reason Evicted. Pods of finished Jobs end as Succeeded or Failed, and the Job controller may manage their clean-up itself, so a clean-up script should skip Pods owned by Jobs unless that is what you want.

Selectors, pagination and errors

Filter on the server whenever you can. label_selector takes the same syntax as kubectl -l, for example app=api,tier!=batch. field_selector supports only a few fields for Pods, such as status.phase, spec.nodeName, metadata.name and metadata.namespace; anything else must be filtered in Python.

On big clusters, ask for results in pages. Pass limit=500, read the token in result.metadata._continue, and pass it back as _continue= until it is empty. This keeps memory and API server load low.

Errors from the API arrive as kubernetes.client.rest.ApiException, with .status holding the HTTP code and .body the JSON message. 404 means the object is gone (often fine during clean-up, because something else deleted it first), 403 means your identity lacks an RBAC permission, 409 means a conflict such as an object that already exists, and 429 means you are being rate limited. Handle the expected ones and let the rest stop the script.

  • Every list call accepts label_selector, field_selector, limit and _continue
  • Check e.status, not the message text, when handling ApiException
  • watch.Watch().stream(v1.list_namespaced_pod, namespace="prod") streams changes instead of polling

Safe clean-ups and least-privilege RBAC

A clean-up script deletes things, so build safety in. Default to a dry run that prints what it would delete. Show the target context. Limit the scope with namespaces or labels, and skip system namespaces like kube-system unless asked. Add a minimum age, for example only Pods that failed more than an hour ago, so you do not delete something a person is still debugging.

The API also has its own server-side dry run: passing dry_run="All" to a delete or create call makes the API server run validation and admission checks without saving anything. It is a good test that your permissions are correct.

When the script runs in the cluster as a CronJob, give it its own ServiceAccount and only the rights it needs. Listing and deleting Pods in all namespaces needs a ClusterRole with verbs get, list and delete on pods in the core API group, bound with a ClusterRoleBinding. Never bind it to cluster-admin. Test with kubectl auth can-i delete pods --as=system:serviceaccount:ops:pod-cleaner.

SequenceA clean-up CronJob run inside the cluster
CronJob Pod
API server
RBAC check
Failed Pod
  1. 1List Pods, phase=Failed, with SA token
    CronJob Pod to API server: List Pods, phase=Failed, with SA token
  2. 2May pod-cleaner list pods?
    API server to RBAC check: May pod-cleaner list pods?
  3. 3Allowed by ClusterRole
    RBAC check to API server: Allowed by ClusterRole
  4. 4Return matching Pods
    API server to CronJob Pod: Return matching Pods
  5. 5Delete Pods older than 1 hour
    CronJob Pod to API server: Delete Pods older than 1 hour
  6. 6Pod removed
    API server to Failed Pod: Pod removed

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Load kubeconfig with the Python client~1h
  2. 2
    List pods and their statuses~1h
  3. 3
    Script a clean-up of failed pods~1h

Key points

  • config.load_kube_config uses your local kubeconfig; load_incluster_config works inside Pods.
  • Field and label selectors filter on the server, so less data comes back.
  • Inside a cluster, the script's ServiceAccount needs RBAC permissions for its actions.
  • Default to dry run, exactly as with AWS clean-up scripts.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import sys
from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()
apply = "--apply" in sys.argv
pods = v1.list_pod_for_all_namespaces(field_selector="status.phase=Failed")
for pod in pods.items:
    ns, name = pod.metadata.namespace, pod.metadata.name
    print("DELETE" if apply else "DRY RUN", ns, name)
    if apply:
        v1.delete_namespaced_pod(name, ns)

Find failed Pods everywhere; delete only with --apply.

Report unhealthy containers across the cluster

Goal: list every container that is waiting with a problem reason or has restarted more than 3 times. Step 1: load config and create CoreV1Api. Step 2: list Pods in pages of 500 so big clusters stay cheap. Step 3: for each Pod, loop over container_statuses, guarding against None for Pending Pods. Step 4: print namespace, Pod, container, reason and restarts. This catches CrashLoopBackOff Pods that a phase check would miss.

python
from kubernetes import client, config

config.load_kube_config()
v1 = client.CoreV1Api()
token = None
while True:
    page = v1.list_pod_for_all_namespaces(limit=500, _continue=token)
    for pod in page.items:
        for cs in pod.status.container_statuses or []:
            reason = cs.state.waiting.reason if cs.state.waiting else ""
            if reason or cs.restart_count > 3:
                print(pod.metadata.namespace, pod.metadata.name, cs.name, reason, cs.restart_count)
    token = page.metadata._continue
    if not token:
        break

RBAC for a Pod clean-up CronJob

Step 1: create a ServiceAccount pod-cleaner in an ops namespace. Step 2: a ClusterRole allows only get, list and delete on Pods in the core group (the empty string). Step 3: a ClusterRoleBinding gives that role to the ServiceAccount. Step 4: set serviceAccountName: pod-cleaner in the CronJob's Pod spec, and the script uses load_incluster_config. Step 5: verify with kubectl auth can-i, which should say yes for delete pods and no for delete deployments.

yaml
apiVersion: v1
kind: ServiceAccount
metadata: { name: pod-cleaner, namespace: ops }
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata: { name: pod-cleaner }
rules: [{ apiGroups: [""], resources: [pods], verbs: [get, list, delete] }]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata: { name: pod-cleaner }
roleRef: { apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: pod-cleaner }
subjects: [{ kind: ServiceAccount, name: pod-cleaner, namespace: ops }]

Quick reference

  • pip install kubernetes, then: from kubernetes import client, config
  • config.load_kube_config(context="kind-dev") picks a cluster explicitly
  • config.load_incluster_config() uses the Pod's ServiceAccount token
  • Pod phase can say Running while a container is in CrashLoopBackOff; check container_statuses
  • Field selectors for Pods: status.phase, spec.nodeName, metadata.name, metadata.namespace
  • Use limit= and metadata._continue to page through large lists
  • Pass dry_run="All" to have the API server validate a change without saving it
  • kubectl auth can-i delete pods --as=system:serviceaccount:ns:name tests RBAC

Common mistakes

  • Running against the wrong context because kubeconfig points at production.
  • Granting cluster-admin to a script that only needs to list and delete Pods.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which class do you use to list Deployments?

Question 2

2A Pod is in CrashLoopBackOff. What does pod.status.phase most likely show?

Question 3

3Your script gets ApiException with status 403. What does it mean?

Question 4

4Why can pod.status.container_statuses be None?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Print the current context name, then the name, phase and node of every Pod in the default namespace.

  2. Exercise 2medium

    Write a function that loads in-cluster config if available and falls back to kubeconfig, then counts Pods per phase across all namespaces.

  3. Exercise 3hard

    Extend the failed-Pod clean-up: skip kube-system, skip Pods failed less than one hour ago, ignore 404 on delete, and stay in dry run unless --apply is given.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Which Python library should I use for Kubernetes?
The official kubernetes package from the kubernetes-client project is the standard choice. Smaller wrappers like kr8s and lightkube exist with friendlier APIs, but the official one covers every resource.
Is there an async Kubernetes client for Python?
Yes, kubernetes_asyncio is a separate package with the same API shape built on asyncio, useful for operators and tools that watch many resources.
How do I apply a YAML file from Python?
kubernetes.utils.create_from_yaml(api_client, "file.yaml") creates the objects in a file. It does not do a full kubectl apply style update, so for updates use patch methods or call kubectl.
Can my script watch for changes instead of polling?
Yes. watch.Watch().stream() wraps a list method and yields ADDED, MODIFIED and DELETED events as they happen. Be ready to restart the watch when it times out.

Go deeper

ShareXLinkedInWhatsApp