Interview Prep/Python for DevOps/Kubernetes, Docker & SSH clients

How do you list pods with high restart counts using the Python client?

BeginnerConceptKubernetes, Docker & SSH clients
Answer
v1 = client.CoreV1Api()
for pod in v1.list_pod_for_all_namespaces(watch=False, limit=500).items:
    for cs in pod.status.container_statuses or []:
        if cs.restart_count > 5:
            reason = cs.last_state.terminated.reason if cs.last_state.terminated else "-"
            print(pod.metadata.namespace, pod.metadata.name, cs.name, cs.restart_count, reason)

Note container_statuses can be None for pending pods. For large clusters, paginate with limit and _continue=resp.metadata._continue, and use label_selector/field_selector to filter on the server.

All Python for DevOps questions Roadmap: Python for automation

More on Kubernetes, Docker & SSH clients