OpenShift - List Namespaces using Python

by
Jeremy Canfield |
Updated: June 01 2025
| OpenShift articles
The openshift package can be used to interact with OpenShift in Python. pip install can be used to install the OpenShift package.
pip install openshift
You may want to first check out my article FreeKB - OpenShift - Login into OpenShift using Python.
And here is an example of how you could log into OpenShift with a username and password and list all projects.
#!/usr/bin/python
from kubernetes import client
from openshift.dynamic import DynamicClient
from openshift.helper.userpassauth import OCPLoginConfiguration
apihost = 'https://api.openshift.example.com:6443'
username = 'john.doe'
password = 'itsasecret'
kubeConfig = OCPLoginConfiguration(ocp_username=username, ocp_password=password)
kubeConfig.host = apihost
kubeConfig.verify_ssl = False
kubeConfig.get_token()
k8s_client = client.ApiClient(kubeConfig)
dyn_client = DynamicClient(k8s_client)
v1_namespaces = dyn_client.resources.get(api_version='v1', kind='Namespace')
namespaces_list = v1_projects.get()
for namespace in namespaces_list.items:
print(namespace.metadata.name)
Here is an example of how you can return a specific project (my-project in this example).
#!/usr/bin/python
from kubernetes import client
from openshift.dynamic import DynamicClient
from openshift.helper.userpassauth import OCPLoginConfiguration
apihost = 'https://api.openshift.example.com:6443'
username = 'john.doe'
password = 'itsasecret'
kubeConfig = OCPLoginConfiguration(ocp_username=username, ocp_password=password)
kubeConfig.host = apihost
kubeConfig.verify_ssl = False
kubeConfig.get_token()
k8s_client = client.ApiClient(kubeConfig)
dyn_client = DynamicClient(k8s_client)
v1_namespaces = dyn_client.resources.get(api_version='v1', kind='Namespace')
my_project = v1_projects.get(name="my-project")
print(my_project)
print(f"project name = {my_project.metadata.name}")
Here is a bit more of a practical example with try / except / else error handling.
#!/usr/bin/python
import sys
from kubernetes import client
from kubernetes.client.rest import ApiException
from openshift.dynamic import DynamicClient
from openshift.helper.userpassauth import OCPLoginConfiguration
kubeConfig = OCPLoginConfiguration(ocp_username='john.doe', ocp_password='itsasecret')
kubeConfig.host = 'https://api.openshift.example.com:6443'
kubeConfig.verify_ssl = False
kubeConfig.get_token()
k8s_client = client.ApiClient(kubeConfig)
dyn_client = DynamicClient(k8s_client)
try:
v1_namespaces = dyn_client.resources.get(api_version='v1', kind='Namespace')
except ApiException as exception:
print(f"got the following exception - {exception}")
sys.exit(1)
namespaces_list = v1_projects.get()
for namespace in namespaces_list .items:
print(namespace.metadata.name)
Did you find this article helpful?
If so, consider buying me a coffee over at