【问题标题】:How can I get a list of all namespaces within a specific Kubernetes cluster, using the Kubernetes API?如何使用 Kubernetes API 获取特定 Kubernetes 集群中所有命名空间的列表?
【发布时间】:2019-09-07 18:58:36
【问题描述】:

我需要使用 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 吗?

【问题讨论】:

    标签: kubernetes namespaces cluster-computing


    【解决方案1】:

    如果您看到 kube_config 模块的 source code,您可以通过方法 load_kube_config 使用不同的参数来选择您的集群:

    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 是一个使用上下文参数与单个 kubeconfig 文件 来迭代多个集群的示例。在 kubernetes 文档中有一个关于 Merging kubeconfig files 的条目。基本上在拥有具有多个上下文的配置文件后,您可以使用config.load_kube_config(config_file=file) 加载文件并使用client.load_kube_config(context="context2') 加载上下文

    附:如果您想使用默认路径 ('~/.kube/config') 中的配置文件,或者如果您在 KUBECONFIG 环境变量中设置路径。

    【讨论】:

    • 维克多,这就是我现在正在做的事情。我更喜欢通过 API 而不是使用文件来处理这个问题,但它对我来说工作得很好。谢谢。
    • 使用 kubectl 快速更改上下文的一种方法是使用 KUBECONFIG 环境变量。不幸的是,Kubernetes API 中有一个issue,它在这个变量中不接受多个上下文。
    【解决方案2】:

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

    显然你只需要替换

    list_pod_for_all_namespaces()
    

    list_namespace()
    

    【讨论】:

    • 我使用了 list_namespace(),它列出了集群的所有命名空间,但它需要一个 .kube 配置文件来指定集群。由于我需要从多个集群中获取命名空间,所以我使用的是 Victor Val 的多个配置文件的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2018-08-05
    • 2022-01-01
    • 1970-01-01
    • 2016-11-09
    • 2019-04-16
    • 1970-01-01
    • 2022-06-26
    相关资源
    最近更新 更多