如何使用 Kubernetes API 获取特定 Kubernetes 集群中所有命名空间的列表?

How can I get a list of all namespaces within a specific Kubernetes cluster, using the Kubernetes API?

我需要使用 Kubernetes API 获取特定 Kubernetes 集群中所有命名空间的列表。因为我需要在我的 Python 程序中循环遍历多个集群,所以我需要在每次调用 API.

时指定集群

一种选择是使用 list_namespace(),如 https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md

中所述

但是,API 不允许我指定集群。它从我的 .kube 配置文件中的当前上下文中获取集群。如果我删除或重命名配置文件,API 调用将完全失败。

我还在 https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/ExtensionsV1beta1Api.md

找到了一个扩展 API

不幸的是,没有 API 可以检索命名空间列表。还有其他一些我不知道的 API 吗?

你会检查这个吗example
在那里您可以在多个上下文之间导航并列出所有名称空间

中的所有 pods

显然你只需要更换

list_pod_for_all_namespaces()

list_namespace()

如果您看到 kube_config 模块的 source code,您可以在方法 load_[=36= 中使用不同的参数] 到 select 您的集群:

def load_kube_config(config_file=None, context=None,
                     client_configuration=None,
                     persist_config=True):
    """Loads authentication and cluster information from kube-config file
    and stores them in kubernetes.client.configuration.
    :param config_file: Name of the kube-config file.
    :param context: set the active context. If is set to None, current_context
        from config file will be used.
    :param client_configuration: The kubernetes.client.Configuration to
        set configs to.
    :param persist_config: If True, config file will be updated when changed
        (e.g GCP token refresh).
    """

如果我对代码的理解正确,您可以执行以下操作:

from kubernetes import client, config
for file in files:
    config.load_kube_config(config_file=file)
    v1 = client.CoreV1Api()
    response = v1.list_namespace()
    print(response)

编辑:This is an example that uses the context argument with a single kubeconfig file to iterate over multiple clusters. In the kubernetes docs there is an entry on Merging kubeconfig files。基本上在具有多个上下文的配置文件之后,您可以使用 config.load_kube_config(config_file=file) 加载文件并使用 client.load_kube_config(context="context2')

加载上下文

P.S。如果要在默认路径中使用配置文件,则不需要使用 config.load_kube_config() ('~/.kube/config') 或者如果您在 KUBECONFIG 环境变量中设置路径。