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.

Secrets file apiVersion: v1 kind: Secret metadata: name: wordpress-secrets type: Opaque data: username: d293IHlvdSBkZWNvZGVkIGl0 password: Z29vZCBmb3IgeW91 host: bm90aGluZyBqdWljeSB0aG91Z2g= 1 2 3 4 5 6 7 8 9 apiVersion : v1 kind : Secret metadata : name : wordpress-secrets type : Opaque data : username : d293IHlvdSBkZWNvZGVkIGl0 password : Z29vZCBmb3IgeW91 host : bm90aGluZyBqdWljeSB0aG91Z2g=

Then configure your pod definition to use the secrets.

Deployment file apiVersion: extensions/v1beta1 kind: Deployment metadata: name: wordpress-deployment spec: replicas: 2 strategy: type: RollingUpdate template: metadata: labels: app: wordpress visualize: "true" spec: containers: - name: "wordpress" image: "wordpress" ports: - containerPort: 80 env: - name: WORDPRESS_DB_USER valueFrom: secretKeyRef: name: wordpress-secrets key: username - name: WORDPRESS_DB_PASSWORD valueFrom: secretKeyRef: name: wordpress-secrets key: password - name: WORDPRESS_DB_HOST valueFrom: secretKeyRef: name: wordpress-secrets key: host 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 apiVersion : extensions/v1beta1 kind : Deployment metadata : name : wordpress-deployment spec : replicas : 2 strategy : type : RollingUpdate template : metadata : labels : app : wordpress visualize : "true" spec : containers : - name : "wordpress" image : "wordpress" ports : - containerPort : 80 env : - name : WORDPRESS_DB_USER valueFrom : secretKeyRef : name : wordpress-secrets key : username - name : WORDPRESS_DB_PASSWORD valueFrom : secretKeyRef : name : wordpress-secrets key : password - name : WORDPRESS_DB_HOST valueFrom : secretKeyRef : name : wordpress-secrets key : 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.