I would like to create a kubectl
cron job that auto delete secrets older than "x" days age, except the latest 2 versions. The Apps in the cluster use these secrets for config, but they get created with every deploy and needs clean up after the fact.
CodePudding user response:
You can use the
kubectl delete secret $(kubectl get secret | awk 'match($5,/[0-9] d/) {print $1}')
You can parse the JSON like you can use the seconds (update 86400) as per need of xdays and write other conditions of the versions.
However, I don't think you can maintain versions with k8s secret, if you are using any external secret
you can parse the version in JSON by modifying the command.
kubectl get externalsecret ....
Use jq command line to parse the JSON:
kubectl get secrets -o json | jq -r "[.items[] | {name: .metadata.name, startTime: .metadata.creationTimestamp | fromdate } | select(.startTime < (now | . - 86400))]" | jq -r ".[].name"
Extra :
If you don't want to use the kubectl you can use the Python or other language with client library and manage the secret and run that Docker image into k8s cronjob
Client libraries: https://kubernetes.io/docs/reference/using-api/client-libraries/