我需要使用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模块的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文件的context参数来迭代多个集群。在kubernetes文档中有一个关于Merging kubeconfig files的条目。基本上在具有多个上下文的配置文件之后,您可以使用config.load_kube_config(config_file=file)
加载文件并使用client.load_kube_config(context="context2')
加载上下文
附:如果要在默认路径('〜/ .kube / config')中使用配置文件,或者在KUBECONFIG环境变量中设置路径,则不需要使用config.load_kube_config()。
你能看看这个example吗? 在那里,您可以在多个上下文之间导航,并列出所有名称空间中的所有窗格
显然你只需要更换
list_pod_for_all_namespaces()
同
list_namespace()