Getting Kubernetes namespaces with Python

Johan Louwers
2 min readNov 4, 2021

In Kubernetes, namespaces provides a mechanism for isolating groups of resources within a single cluster. Names of resources need to be unique within a namespace, but not across namespaces. Namespace-based scoping is applicable only for namespaced objects (e.g. Deployments, Services, etc) and not for cluster-wide objects (e.g. StorageClass, Nodes, PersistentVolumes, etc).

Finding namespaces

Finding namespaces can, obviously, be done using command line tool kubectl and any other tool such as the kubernetes dashboard which provides you a graphical user interface for administrating your kubernetes cluster.

While the kubectl interface gives you options to start integrating things into an automated approach in many cases you might want to include this functionality into a real programming language such as python. For this you can leverage the Kubernetes Python Client and fully start automating Kubernetes in a programmable fashion.

Using Python to find the namespaces

Finding all available namespaces with Python requires you to include the Python Client for Kubernetes in your code. The below code snippet shows how you can obtain all namespaces in Kubernetes.

Secure the use of Python

The python client will use, by default, the configuration located in ~/kube/config while this is an easy way of ensuring your Python code can connect it comes with a warning. When you distribute your code, for example make it part of the logic in a container to become self-aware, you want to ensure the rights associated with the config file you distribute are limited to only the needed. A common mistake is to push a very open set of rights which is a direct security issue. Commonly restricted read only is enough for cases like this.

About the author(s)
Johan Louwers is Chief Enterprise Architect within Oracle as well as Director Cloud Native Architecture where he leads an highly specialised complex engineering team responsible for supporting Enterprises in adopting a cloud native strategy from both the technology as well as the Enterprise Architecture point of view. Views expressed in this post are personnel and do not necessarily reflect the views of Oracle.



Johan Louwers

Johan Louwers is a technology enthousiasts with a long background in supporting enterprises and startups alike as CTO, Chief Enterprise Architect and developer.