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

如何用Azure Python SDK与K8s Python Client获取AKS集群Pod的CPU限制

解决Azure AKS集群Pod CPU限制查询问题

核心问题处理:传递KubeConfig到Kubernetes Python客户端

从Azure SDK获取的kubeconfig是二进制字节流,需先解码为UTF-8字符串,再通过Kubernetes客户端config.load_kube_config()的config_str参数直接传入,无需写入本地文件。

完整实现代码

from azure.identity import DefaultAzureCredential
from azure.mgmt.containerservice import ContainerServiceClient
from kubernetes import client, config

# Azure认证与KubeConfig获取
credential = DefaultAzureCredential(exclude_cli_credential=True)
subscription_id = "XXX"
resource_group_name= 'MY-SUB'
cluster_name = "my-aks-clustername" 
container_service_client = ContainerServiceClient(credential, subscription_id)

# 将二进制KubeConfig解码为字符串
kubeconfig_bytes = container_service_client.managed_clusters.list_cluster_user_credentials(
    resource_group_name, cluster_name
).kubeconfigs[0].value
kubeconfig_str = kubeconfig_bytes.decode('utf-8')

# 加载配置到Kubernetes客户端
config.load_kube_config(config_str=kubeconfig_str)

# 查询所有Pod的CPU限制
v1 = client.CoreV1Api()
print("Pod名称\t命名空间\tCPU限制")
ret = v1.list_pod_for_all_namespaces(watch=False)
for pod in ret.items:
    pod_name = pod.metadata.name
    namespace = pod.metadata.namespace
    # 遍历Pod内的每个容器获取CPU限制
    for container in pod.spec.containers:
        if container.resources and container.resources.limits:
            cpu_limit = container.resources.limits.get('cpu', '未设置')
        else:
            cpu_limit = '未设置'
        print(f"{pod_name}\t{namespace}\t{cpu_limit}")

关键细节说明

  • kubeconfigs[0].value返回二进制数据,必须通过decode('utf-8')转换为字符串,才能被Kubernetes客户端识别。
  • 使用config.load_kube_config(config_str=kubeconfig_str)直接从内存加载配置,完全规避文件IO和subprocess调用,符合要求。
  • 单个Pod可能包含多个容器,需遍历pod.spec.containers逐个获取资源限制;若容器未配置CPU限制,返回"未设置"作为默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:35:21