Search code examples
pythonkubernetespersistent-volume-claims

Get details of persistent volume claim using python k8s client


I'm trying to get details of persistentvolumeclaim such as "Used By" which you can get when you run kubectl describe pvc [your-pvc-name] but I'm trying to get that using python k8s client. I'm able to get YAML of the pvc through readNamespacedPersistentVolumeClaim() function but it doesn't contain the "Used By". How to use python k8s client to get details of a persistentvolumeclaim such as "Used By".


Solution

  • from kubernetes import client
    
    
    def get_pod_related_to_pvc(pvc_obj, pv_obj):
     v1 = client.CoreV1Api()
     pod = None
     pod_list = v1.list_namespaced_pod(pvc_obj.metadata.namespace)
     for pod in pod_list.items:
        for volume in pod.spec.volumes:
            if volume.persistent_volume_claim:
                if (volume.persistent_volume_claim.claim_name == pv_obj.spec.claimRef.name):
                    return pod
    

    This code seems to work perfectly to list all pods with their respective pvc in a namespace from that we can filter out the pod we want.