I need to get a list of all namespaces in a specifc Kubernetes cluster, using the Kubernetes API. Because I need to loop through multiple clusters in my Python program, I need to specify the cluster every time I call the API.
One option is to use list_namespace(), as described in https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md
However, this API doesn't allow me to specify the cluster. It picks up the cluster from the current-context in my .kube config file. If I remove or rename the config file, the API call fails completely.
I also found an extensions API at https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/ExtensionsV1beta1Api.md
Unfortunately, there is no API there to retrieve a list of namespaces. Is there some other API that I am unaware of?
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()
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, config
for 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.