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

使用Python Kubernetes API如何获取当前运行命名空间下的Secret列表?

解决方案

完全可以自动获取当前Pod所在的命名空间,无需硬编码配置,也不需要额外的集群级权限,常用实现方式如下:

Kubernetes 会为所有挂载了 ServiceAccount 的 Pod(默认配置下所有Pod都会自动挂载默认ServiceAccount),自动将当前Pod的命名空间名称写入容器内的 /var/run/secrets/kubernetes.io/serviceaccount/namespace 文件,直接读取即可,不需要调用Kubernetes API,也不需要额外RBAC权限。你可以将该逻辑和本地开发场景的适配逻辑整合,示例代码如下:

from kubernetes import client, config

def get_current_namespace():
    # 集群内运行场景:读取ServiceAccount挂载的命名空间文件
    try:
        with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r") as f:
            return f.read().strip()
    except FileNotFoundError:
        # 本地开发场景:从kubeconfig当前上下文读取命名空间,无配置则返回default
        _, active_context = config.list_kube_config_contexts()
        return active_context["context"].get("namespace", "default")

# 加载配置:优先集群内配置,其次本地kubeconfig
try:
    config.load_incluster_config()
except config.ConfigException:
    config.load_kube_config()

v1 = client.CoreV1Api()
current_ns = get_current_namespace()
# 调用接口列出当前命名空间下的Secret
secrets = v1.list_namespaced_secret(namespace=current_ns)

方案优势

  • 无需修改Pod配置清单,部署到任意命名空间都可以自动识别,不需要手动传递命名空间参数
  • 不需要额外RBAC权限,读取文件是Pod的默认权限,也不需要申请集群级Secret访问权限
  • 同时兼容集群内正式运行、本地开发测试两种场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:36:02