#devops #kubernetes #pattern

When you manage secrets with Kubernetes, you'll be using the kubectl secret suite of commands. There are a few patterns I use to make life a little easier.

First one is to have kubectl ignore errors when deleting a secret which doesn't exist. There is a command-line argument --ignore-not-found which does exactly that:

1$ kubectl delete secret my-secret --ignore-not-found

By adding --ignore-not-found, kubectl will silently ignore the error which is great if you for example use it in a Makefile. In a Makefile, when a command fails (exits with a non-zero exit code), the build will stop. If you are recreating a secret, this is not what you want.

Defining secrets containing environment variables are usually done by using literals:

1$ kubectl create secret generic my-env-vars1 \
2        --from-literal="VAR1=myhost.yellowduck.be" \
3        --from-literal="VAR2=production"
1$ kubectl create secret generic my-env-vars2 \
2        --from-literal="VAR3=secret-key" \
3        --from-literal="VAR4=db-conn"

However, I find this hard to read and it also disables syntax coloring. I prefer to define them in a file with the extension .env (so that Visual Studio Code does syntax highlighting):

my-env-vars1.env

1VAR1=myhost.yellowduck.be
2VAR2=production

my-env-vars2.env

1VAR3=secret-key
2VAR4=db-conn

Once you have these files, loading can be done by using the --from-env-file command-line argument specifying the path of the file in which they are defined:

1$ kubectl create secret generic my-env-vars1 --from-env-file=my-env-vars1.env
1
2$ kubectl create secret generic my-env-vars2 --from-env-file=my-env-vars2.env

The folks at SpaceLift provide a complete guide on how to work with secrets in a Kubernetes cluster.