Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify unused secrets in Kubernetes?

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?

like image 660
adebasi Avatar asked Sep 25 '17 13:09

adebasi


1 Answers

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 Ingresses
  • Pods Volumes spec, like Simon mentioned
  • ImagePullSecrets for private repositories
  • CRDs Custom Resource Definitions

But 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)
like image 93
adebasi Avatar answered Sep 20 '22 14:09

adebasi