Protip: find deployments mounting Kubernetes secret

Alwyn Kik

Useful one-liner to find all workloads that mount a specific secret:

export secret_name=foo kubectl get deploy,statefulset,daemonset,job,cronjob -A -o json | jq -r --arg s $secret_name '.items[] | select([.. | objects | .secretName?, .secretKeyRef?.name, .secretRef?.name, .secret?.name] | any(. == $s)) | "\(.metadata.namespace) \(.kind)/\(.metadata.name)"'

This recursively searches for all secretName, secretKeyRef, secretRef and secret keys, taking into account all forms of referencing a secret ((deploy|sts|ds,job).spec.(job)template assumed):

  • .spec.volumes.secret.secretName - "classic" secret volume
  • .spec.volumes.projected.sources.secret.name - projected source
  • .spec.containers.env.valueFrom.secretKeyRef.name - for a specific environment variable
  • .spec.containers.envFrom.secretRef.name - for populating environment variables from a secret