Check which deployment (if any) is using a secret

9/20/2021

I am replacing a Kubernetes secret and I want to make sure I am catching all places in the cluster which use it.

Is there a way to tell without reading all deployment YAMLs using K8s or helm?

We have multiple services deployed on the same cluster and sharing secrets. Some using Helm, some don't.

-- Tomer Amir
kubernetes
kubernetes-helm
kubernetes-secrets

2 Answers

9/21/2021

You can use secrets in several different ways, it's not always bound as volume. So the most convenient way is to check the secret's namespace for all objects that could use secret in their specs.

For manual check here are two commands, one for checking for the certain secret name references among k8s objects, the second one helps to find the object that contains the secret reference.

kubectl get deployments,statefulsets,daemonsets,cronjobs,jobs,pods -n namespace-name -o yaml | grep  secret_name

kubectl get deployments,statefulsets,daemonsets,cronjobs,jobs,pods -n namespace-name -o yaml | grep -i -e "^ name:"  -e "^  kind" -e secret_name

Annotation can be removed by grep -v annotation -v last-applied or probably even easier grep -v "\"kind".

-- Jakub Siemaszko
Source: StackOverflow

12/16/2021

I used Jakub's answer and modified a little bit to better produce the list of names of deployments and cronjobs using a particular secret's name

This requires jq to function

kubectl get deployments,cronjobs -o json | jq '.items[]|select(.spec.template.spec.containers[]?.env[]?.valueFrom.secretKeyRef.name == "NAME_OF_SECRET") | .metadata.name'
-- Sean Yuan
Source: StackOverflow