I’ve found myself wanting to use Kubernetes Secrets for a while, but I every time I did, I ran into the fact that secrets had to be mounted as files in the container, and then you had to programmatically grab those secrets and turn them into environment variables. This works and there are posts like this great one from my coworker, Aja Hammerly that tell you how to do it.
It always seemed a little suboptimal for me though. Mostly because you had to alter your Docker image in order to use secrets. Then you lose some of the flexibility to use a Dockerfile in both Docker and Kubernetes. It’s not the end of the world – you can write a conditional script – but I never liked doing this. It would be awesome if you could just write Secrets directly to ENV variables.
Well it turns out you can. Right there in the documentation there’s a whole section on Using Secrets as Environment Variables. It’s pretty straightforward:
Make a Secrets file, remembering to base64 encode your secrets.
Then configure your pod definition to use the secrets.
- name: "wordpress"
- containerPort: 80
- name: WORDPRESS_DB_USER
- name: WORDPRESS_DB_PASSWORD
- name: WORDPRESS_DB_HOST
That’s it. It’s a great addition to the secrets API. I’m trying to track down when it was added. It looks like it came in 1.2. The first reference I could find to it in the docs was in this commit updating Kubernetes Documentation for 1.2.