Loading Environment Variables From Secrets in Kubernetes

July 11, 2019

In Kubernetes, it’s a good idea to keep your environment variables in secrets.

You can do this by using kubectl:

$ kubectl create secret generic my-env-vars \
        --from-literal="VAR1=myhost.yellowduck.be" \
        --from-literal="VAR2=production"

One of the frequent use cases is to use these environment variables from a container in a deployment. You can reference them as follows:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
  labels:
    app: my-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-deployment
  template:
    metadata:
      labels:
        app: my-deployment
    spec:
      containers:
      - name: my-deployment
        image: <my-docker-user>/<my-docker-private-repo<
      imagePullSecrets:
      - name: <my-secret-name>
      envFrom:
      - secretRef:
          name: my-env-vars

The nice thing is that you can combine the environment variables from multiple secrets. Imagine you have two secrets containing environment variables:

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

You can use both in your deployment by adding two secretRef values (as envFrom is an array):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-deployment
  labels:
    app: my-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-deployment
  template:
    metadata:
      labels:
        app: my-deployment
    spec:
      containers:
      - name: my-deployment
        image: <my-docker-user>/<my-docker-private-repo<
      imagePullSecrets:
      - name: <my-secret-name>
      envFrom:
      - secretRef:
          name: my-env-vars1
      - secretRef:
          name: my-env-vars2