Infrastructure at your Service

David Barbarin

How to get a big picture of K8s pods and PVs by script

A couple of weeks ago, during an internal dbi services workshop about Docker and K8s, I got an interesting question: is it possible to get a big picture of pods connected to one specific persistent volume (PV) by using kubectl command?

It was an interesting question because if we go through the usual kubectl command, it doesn’t provide natively the desired output. In fact, one one hand we get information about PVs and their related persistent volume claims (PVC) and one other hand Pods with their PVCs.

I didn’t find out any relevant result with my google-fu so here my contribution with a bash script that provides the overall picture of pods that are tied to a specific PV. It could be helpful in any appropriate way to quickly identify stateful(set) applications like SQL Server databases (and others) and their related storage 🙂

#!/bin/bash

pv=$1

pvcs=$(kubectl get pv --output=json | jq -r --arg PV "$pv" '.items[] | select (.metadata.name==$PV or $PV=="") | "\(.metadata.name)" + "|" + "\(.spec.claimRef.namespace)" + "|" + "\(.spec.claimRef.name)"')

 for pvc in $pvcs 
 do 
     p_pv=$(echo $pvc | cut -d'|' -f1)
     p_ns=$(echo $pvc | cut -d'|' -f2)
     p_pvc=$(echo $pvc | cut -d'|' -f3)
  
     echo "===================================================="
     echo "==> pv: $p_pv"
     kubectl get pods -n $p_ns --output=json | jq -c --arg CLAIM "$p_pvc" '.items[] | {Pod: .metadata.name, Namespace: .metadata.namespace, ClaimName: .spec | select ( has ("volumes") ).volumes[] | select( has ("persistentVolumeClaim") ).persistentVolumeClaim | select (.claimName==$CLAIM) }'
 done

 

If you provide as input a specific PV you will get a picture of all pods tied to it otherwise all PVs and their linked pods will be shown in the output.

  • With a specific PV as input
$ ./get_pods_by_pv.sh pvc-a969c5d7-d654-11e9-ab0d-06376ae701a9
====================================================
==> pv: pvc-a969c5d7-d654-11e9-ab0d-06376ae701a9
{"Pod":"mssql-deployment-85bfdfc66c-ht4wl","Namespace":"ci","ClaimName":{"claimName":"mssql-data"}}

 

  • No PV as input
$ ./get_pods_by_pv.sh
====================================================
==> pv: pvc-a969c5d7-d654-11e9-ab0d-06376ae701a9
{"Pod":"mssql-deployment-85bfdfc66c-ht4wl","Namespace":"ci","ClaimName":{"claimName":"mssql-data"}}
====================================================
==> pv: pvc-eb90982d-d654-11e9-ab0d-06376ae701a9
{"Pod":"mssql-deployment-2-7db97bf7d-9bsp6","Namespace":"ci","ClaimName":{"claimName":"mssql-data-2"}}
====================================================
==> pv: pvc-f9c14523-d61e-11e9-ab0d-06376ae701a9

 

Feel free to comment, to share or to improve!

See you!

By David Barbarin

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

David Barbarin
David Barbarin

Principal Consultant & Microsoft Technology Leader