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

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


If you see the source code of the kube_config module you can use different arguments with the method load_kube_config to select your cluster:

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).    """

If I understood the code correctly, you can do somewhat like the following:

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

EDIT: 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. Basically after having a config file with multiple contexts you can load the file with config.load_kube_config(config_file=file) and load contexts with client.load_kube_config(context="context2')

P.S. You don't need to use config.load_kube_config() if you want to use a config file in the default path ('~/.kube/config') or if you set a path in the KUBECONFIG environment variable.


Would you check this example
There you can navigate between multiple contexts and list all pods within all namespaces

Apparently you just need to replace

list_pod_for_all_namespaces()

with

list_namespace()