Bootstrap FreeKB - OpenShift - List Persistent Volumes using Python
OpenShift - List Persistent Volumes using Python

Updated:   |  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 Persistent Volumes.

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_persisent_volumes = dyn_client.resources.get(api_version='v1', kind='PersistentVolume')
persisent_volumes = v1_persisent_volumes.get()

for persisent_volume in persisent_volumes.items:
  print(persisent_volume)

 

Here is a bit more of a practical example with try / except / else error handling.

import sys
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)

try:
  v1_persisent_volumes = dyn_client.resources.get(api_version='v1', kind='PersistentVolume')
except ApiException as exception:
  print(f"got the following exception - {exception}")
  sys.exit(1)
  
persisent_volumes = v1_persisent_volumes.get()

for persisent_volume in persisent_volumes.items:
  print(persisent_volume)

 

And here is now you could list a specific Persistent Volume.

persisent_volume = v1_persisent_volumes.get(name='my-persistent-volume')

 

And here is how you can print a specific key in the response using dot notation.

persisent_volume = v1_persisent_volumes.get(name='my-persistent-volume')
print(persisent_volume.metadata.name)

 

Or like this.

persisent_volume = v1_persisent_volumes.get(name='my-persistent-volume')
print(persisent_volume['metadata']['name'])

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d0a1a2 in the box below so that we can be sure you are a human.