
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 every pods in all namespaces.
#!/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_pods = dyn_client.resources.get(api_version='v1', kind='Pod')
pods_list = v1_pods.get()
for pod in pods_list.items:
print(pod.metadata.name)
Here is now you could list all pods in a specific namespace.
pods = v1_pods.get(namespace='my-project')
Here is now you could list a specific pod in a specific namespace.
pod = v1_pods.get(namespace='my-project', name='my-pod')
If your request returns a single result, you should be able to print a specific key in the response without a loop.
pod = v1_pods.get(namespace='my-project', name='my-pod')
print(pod.metadata.name)
If your request returns two or more results, here is how you can loop through the results.
pods = v1_pods.get()
for pod in pods.items:
print(secret)
And here is how you can print a specific key in the response using dot notation.
pods = v1_pods.get()
for pod in pods.items:
print(pod.metadata.name)
Or like this.
pods = v1_pods.get()
for pod in pods.items:
print(pod['metadata']['name'])
Did you find this article helpful?
If so, consider buying me a coffee over at