You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Kubernetes Python Client按标签选择器获取命名空间级资源?

使用Kubernetes Python Client实现kubectl -n namespace get all -l key=value的功能

kubectl get all本质是查询Kubernetes预定义的一组常用资源类型,包括Pod、Service、Deployment、ReplicaSet、StatefulSet、DaemonSet、Job、CronJob。要通过Python Client实现等价功能,需针对这些资源类型分别发起查询,同时指定命名空间和标签选择器。

实现步骤与代码示例

  1. 先安装Kubernetes Python Client:
pip install kubernetes
  1. 完整实现代码如下:
from kubernetes import client, config

def get_all_resources(namespace, label_selector):
    # 加载K8s配置(本地环境从~/.kube/config读取,集群内Pod自动加载集群配置)
    config.load_kube_config()
    
    # 初始化各资源对应的API客户端
    core_v1 = client.CoreV1Api()
    apps_v1 = client.AppsV1Api()
    batch_v1 = client.BatchV1Api()
    # 注意:若K8s版本低于v1.21,CronJob需使用BatchV1beta1Api
    # batch_v1beta1 = client.BatchV1beta1Api()

    # 定义要查询的资源类型及对应API方法
    resources = [
        ("Pods", core_v1.list_namespaced_pod, namespace, label_selector),
        ("Services", core_v1.list_namespaced_service, namespace, label_selector),
        ("Deployments", apps_v1.list_namespaced_deployment, namespace, label_selector),
        ("ReplicaSets", apps_v1.list_namespaced_replica_set, namespace, label_selector),
        ("StatefulSets", apps_v1.list_namespaced_stateful_set, namespace, label_selector),
        ("DaemonSets", apps_v1.list_namespaced_daemon_set, namespace, label_selector),
        ("Jobs", batch_v1.list_namespaced_job, namespace, label_selector),
        # 针对K8s < v1.21,替换为下面一行
        # ("CronJobs", batch_v1beta1.list_namespaced_cron_job, namespace, label_selector),
        ("CronJobs", batch_v1.list_namespaced_cron_job, namespace, label_selector),
    ]

    # 遍历查询所有目标资源
    for resource_name, api_method, ns, labels in resources:
        print(f"\n--- {resource_name} ---")
        try:
            response = api_method(namespace=ns, label_selector=labels)
            for item in response.items:
                print(f"名称: {item.metadata.name}, 状态: {item.status}")
        except Exception as e:
            print(f"获取{resource_name}失败: {str(e)}")

if __name__ == "__main__":
    # 替换为你的目标命名空间和标签选择器
    target_namespace = "namespace"
    target_labels = "key=value"
    get_all_resources(target_namespace, target_labels)

关键注意事项

  • label_selector参数直接对应kubectl命令中的-l key=value,格式完全一致,支持多标签组合(如key1=value1,key2=value2)。
  • 不同Kubernetes版本的资源API版本存在差异:比如CronJob在v1.21及以后版本从batch/v1beta1升级为batch/v1,需根据集群版本调整对应的API客户端。
  • 若在Kubernetes集群内部的Pod中运行代码,可使用config.load_incluster_config()替代config.load_kube_config(),自动加载集群内的服务账户配置。

内容的提问来源于stack exchange,提问作者romlym

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 03:47:39