Today I found myself in the need of finding out if one of my persistent volume claims was still in use. Here's how I did it.

Quick overview, I've been beating up my cluster with a lot of junk and have a lot of persistent volume claims (PVC's) sitting out there. I suspect there are some that aren't in use anymore. I want to clean them up, so first I needed a way of getting a list of all of the volumes in use by my pods, which is what this post is about.

To accomplish this task, I used kubectl and jq to output a JSON object that contains the namespace, pod name, and volumes associated with it. It doesn't filter the type of volumes, so it will also include things like config map and secret names when they are mounted as volumes.

The command I used is this:

kubectl get pods -o json | jq '[.items[] | { namespace: .metadata.namespace, podname: .metadata.name, volumes: [.spec.volumes[]?] }]'

An example of the output is this:

[
  {
    "namespace": "elasticsearch",
    "podname": "elasticsearch-master-0",
    "volumes": [
      {
        "name": "elasticsearch-master",
        "persistentVolumeClaim": {
          "claimName": "elasticsearch-master-elasticsearch-master-0"
        }
      },
      {
        "name": "default-token-tsp7d",
        "secret": {
          "defaultMode": 420,
          "secretName": "default-token-tsp7d"
        }
      }
    ]
  },
  {
    "namespace": "elasticsearch",
    "podname": "elasticsearch-master-1",
    "volumes": [
      {
        "name": "elasticsearch-master",
        "persistentVolumeClaim": {
          "claimName": "elasticsearch-master-elasticsearch-master-1"
        }
      },
      {
        "name": "default-token-tsp7d",
        "secret": {
          "defaultMode": 420,
          "secretName": "default-token-tsp7d"
        }
      }
    ]
  }
]

With that simple output you could easily search through it with code, vi, notepad, less, or whatever other tool you want to use.