Thursday, July 7, 2022

kubenrnetes api to get pod details

 Reference: https://www.velotio.com/engineering-blog/kubernetes-python-client


from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
ret = v1.list_namespaced_pod(namespace='default', watch=False)
for i in ret.items:
    #print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    # print(i.status)  # .phase)
    if i.status.phase.lower() == "running":
        print(i.metadata.name, " :pod state is running")
    else:
        for container in i.status.container_statuses:
            if container.ready == True:
                print(container.name, " :State is True")
            else:
                print("For pod: ", i.metadata.name, " Container: ", container.name,
                      " is not up with reason: ", container.state.waiting.reason)

Added condition to skip if the waiting object is None value.


from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
ret = v1.list_namespaced_pod(namespace='default', watch=False)
for i in ret.items:
    #print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
    if not (i.status.phase in ["Running", "Completed", "Succeeded"]):
        for container in i.status.container_statuses:
            if container.ready == True:
                print(container.name, " :State is True")
            else:
                if(container.state.waiting is not None):
                  print("For pod: ", i.metadata.name, " Container: ", container.name," is not up with reason: ", container.state.waiting.reason)
                else:
                  print("For pod: ", i.metadata.name, " Container: ", container.name)

No comments:

Post a Comment