Python: current namespace

Created on 16 Oct 2017  路  5Comments  路  Source: kubernetes-client/python

how can i get the current namespace in used within the code?

Most helpful comment

Unfortunately this does not work when using in-cluster config. The best I could find is reading the kubernetes secret directly like:

>>> from kubernetes import client, config
>>> config.load_incluster_config()
>>> kube_client = client.CoreV1Api()
>>> current_namespace = open("/var/run/secrets/kubernetes.io/serviceaccount/namespace").read()
>>> pods = kube_client.list_namespaced_pod(current_namespace).items

All 5 comments

"Current namespace" is not supported by the library - if a command needs namespace as an argument it will have to be passed explicit.

I believe current namespace is available in current context. See: https://github.com/kubernetes-client/python/issues/360

EG:

>>> from kubernetes import client, config
>>> config.load_kube_config()
>>> config.list_kube_config_contexts()[1]
{'name': 'btgke', 'context': {'namespace': 'ralph', 'cluster': 'btgke', 'user': 'btgke-admin'}}

So what you want is:

>>> current_namespace = config.list_kube_config_contexts()[1]['context']['namespace']
>>> print(current_namespace)
ralph

Unfortunately this does not work when using in-cluster config. The best I could find is reading the kubernetes secret directly like:

>>> from kubernetes import client, config
>>> config.load_incluster_config()
>>> kube_client = client.CoreV1Api()
>>> current_namespace = open("/var/run/secrets/kubernetes.io/serviceaccount/namespace").read()
>>> pods = kube_client.list_namespaced_pod(current_namespace).items
>>> config.list_kube_config_contexts()[1]
{'context': {'cluster': 'dev-svc-4.7-122301', 'user': 'admin'}, 'name': 'admin'}

does not show any namespace key

In mac, with docker-desktop deployed, also can not show namespace in context.

>>> from kubernetes import config as kube_config
>>> contexts, active_context = kube_config.list_kube_config_contexts()

>>> contexts
[{'context': {'cluster': 'docker-desktop', 'user': 'docker-desktop'}, 'name': 'docker-desktop'}, {'context': {'cluster': 'docker-desktop', 'user': 'docker-desktop'}, 'name': 'docker-for-desktop'}]

>>> active_context
{'context': {'cluster': 'docker-desktop', 'user': 'docker-desktop'}, 'name': 'docker-desktop'}
>>>
Was this page helpful?
0 / 5 - 0 ratings