I want to rename my k8s Secrets and want to check if there are unused Secrets. Also I would like to know how many and which containers reference a Secret.
Is there a easier way to do this than search for the secret names in all deployments?
Thanks Simon. Based on your answer I created a diff, which shows secrets that are not referenced in the containers env section. Secrets can also be referenced in:
TLS section of IngressesPods Volumes spec, like Simon mentionedImagePullSecrets for private repositoriesCRDs Custom Resource DefinitionsBut for me it is enough to find secrets that are not referenced in environment variables:
diff \
<(kubectl get pods -o jsonpath='{.items[*].spec.containers[*].env[*].valueFrom.secretKeyRef.name}' | xargs -n1 | sort | uniq) \
<(kubectl get secrets -o jsonpath='{.items[*].metadata.name}' | xargs -n1 | sort | uniq)
Update 16.04.2018
I created a more advanced version to find also secrets referenced in volumes, ingress tls and imagePullSecrets. The following snippet will show you all unused secrets for the current namespace.
Caution: The script does not cover all options where secrets can be referenced (e.g. Custom Resource Definitions).
Update 15.06.2021: Added secrets from Pod container spec envFrom[*].secretRef.name as secret source
envSecrets=$(kubectl get pods -o jsonpath='{.items[*].spec.containers[*].env[*].valueFrom.secretKeyRef.name}' | xargs -n1)
envSecrets2=$(kubectl get pods -o jsonpath='{.items[*].spec.containers[*].envFrom[*].secretRef.name}' | xargs -n1)
volumeSecrets=$(kubectl get pods -o jsonpath='{.items[*].spec.volumes[*].secret.secretName}' | xargs -n1)
pullSecrets=$(kubectl get pods -o jsonpath='{.items[*].spec.imagePullSecrets[*].name}' | xargs -n1)
tlsSecrets=$(kubectl get ingress -o jsonpath='{.items[*].spec.tls[*].secretName}' | xargs -n1)
diff \
<(echo "$envSecrets\n$envSecrets2\n$volumeSecrets\n$pullSecrets\n$tlsSecrets" | sort | uniq) \
<(kubectl get secrets -o jsonpath='{.items[*].metadata.name}' | xargs -n1 | sort | uniq)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With