from kubernetes import client, config
# ① 加载 kubeconfig(默认 ~/.kube/config)
# 如果在 Pod 内走 ServiceAccount,换成 config.load_incluster_config()
# config.load_kube_config()
config.load_kube_config(config_file=r"E:\code\py\3108\k8s_client\remote-config\config")
# ② 创建 API 客户端
v1 = client.CoreV1Api()
# ③ 遍历所有命名空间的 Pod
print("{:<30} {:<50} {:<50}".format("NAMESPACE", "POD_NAME", "IMAGE(VERSION)"))
print("-" * 120)
# for pod in v1.list_pod_for_all_namespaces(watch=False).items:
for pod in v1.list_namespaced_pod(namespace="default").items:
ns = pod.metadata.namespace
name = pod.metadata.name
# 一个 Pod 可能多个容器,逐个取镜像
if pod.spec.init_containers is not None:
for c in pod.spec.init_containers:
print("{:<30} {:<50} {:<50}".format(ns, name, c.image))
else:
for c in pod.spec.containers:
print("{:<30} {:<50} {:<50}".format(ns, name, c.image))