OpenShift - Login to OpenShift 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 which will also install some Kubernetes packages.
pip install openshift
And here is an example of how you could log into OpenShift with a username and password and list the 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_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')
project_list = v1_projects.get()
for project in project_list.items:
print(project.metadata.name)
And here is an example of how you could log into OpenShift with a service account token and list the projects.
- FreeKB - OpenShift - Log into OpenShift using a service account token
- FreeKB - OpenShift - Log into OpenShift using a user account token
# import required modules
from kubernetes import client
from openshift.dynamic import DynamicClient
# init client and auth
kubeConfig = client.Configuration()
kubeConfig.api_key_prefix['authorization'] = 'Bearer'
kubeConfig.api_key["authorization"] = 'abc123'
kubeConfig.host = 'https://api.openshift.example.com:6443'
kubeConfig.verify_ssl = False
k8s_client = client.ApiClient(kubeConfig)
dyn_client = DynamicClient(k8s_client)
# get pods
v1_pods = dyn_client.resources.get(api_version='v1', kind='Pod')
pods_list = v1_pods.get()
# loop through results
for pod in pods_list.items:
print(pod.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
apihost = 'https://api.openshift.example.com:6443'
kubeConfig = client.Configuration()
kubeConfig.api_key_prefix['authorization'] = 'Bearer'
kubeConfig.api_key["authorization"] = 'abc123'
kubeConfig.host = apihost
kubeConfig.verify_ssl = False
k8s_client = client.ApiClient(kubeConfig)
dyn_client = DynamicClient(k8s_client)
try:
v1_projects = dyn_client.resources.get(api_version='project.openshift.io/v1', kind='Project')
except ApiException as exception:
print(f"got the following exception - {exception}")
sys.exit(1)
project_list = v1_projects.get()
for project in project_list.items:
print(project.metadata.name)
Did you find this article helpful?
If so, consider buying me a coffee over at