met*_*gia 5 namespaces cluster-computing kubernetes
我需要使用 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 吗?
如果你看到的源代码中的kube_config模块,您可以使用不同的参数与方法load_kube_config来选择您的集群:
Run Code Online (Sandbox Code Playgroud)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)
Run Code Online (Sandbox Code Playgroud)
编辑:这是一个示例,它使用带有单个 kubeconfig 文件的上下文参数来迭代多个集群。在 kubernetes 文档中有一个关于合并 kubeconfig 文件的条目。基本上在拥有具有多个上下文的配置文件后,您可以使用以下命令加载文件config.load_kube_config(config_file=file)并加载上下文client.load_kube_config(context="context2')
PS如果要在默认路径 ( '~/.kube/config' ) 中使用配置文件,或者在 KUBECONFIG 环境变量中设置路径,则不需要使用config.load_kube_config()。