Kubernetes:如何使用 python 获取容器的状态和重启?

Kubernetes: How do I get the status and restarts of a container using python?

我想使用 python kubernetes. I am currently using list_namespaced_pod to get the pods and the container status 获取容器状态和 pod 的重启,我将其解释为 pod 的状态。这可行,但远非理想的解决方案。我正在寻找能为我提供与 kubectl -n $NAMESPACE get pods.

类似信息的信息

您可以执行以下操作,例如,获取所有 pods 及其状态:

api_response = api_instance.list_namespaced_pod(namespace, pretty=pretty, timeout_seconds=timeout_seconds, watch=watch)

for i in api_response.items:
    print(i.metadata.name + " " + i.status.phase)

添加到@rico 的回答中,

for pod in api_response.items:
    status = pod.status.phase    
    container_status = pod.status.container_statuses[0]
    if container_status.started is False or container_status.ready is False:
        waiting_state = container_status.state.waiting
        if waiting_state.message is not None and 'Error' in waiting_state.message:
            status = waiting_state.reason
    print(pod.metadata.name + " " + status)

您还可以循环调用 api 调用 'api_instance.list_namespaced_pod' 来查看状态在线变化,就像 kubectl -n $NAMESPACE get pods -w