A repository of bitesize articles, tips & tricks
(in both English and French) curated by Mirego’s team.

Kubernetes and environment variables update

When declaring a Kubernetes deployment and its containers, we can use envFrom + secretRef to make these containers use environment variables stored inside a Kubernetes Secret.

apiVersion: v1
kind: Secret
metadata:
  name: myapp-secret-environment-variables
type: Opaque
stringData:
  FOO: sample value
  BAR: other sample value
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: myapp-container
          image: gcr.io/myapp:1.0.0
          envFrom:
            - secretRef:
                name: myapp-secret-environment-variables

The myapp-container container in the myapp-deployment pods will have both FOO and BAZ in its runtime environment. Neat.

But what happens if we want to update these environment variables and have containers use the updated values? We cannot simply update the secret data, because it will not trigger a pod restart since the pod specification will not have changed.

We need to create a brand new secret, and change the secretRef value in the pod template specification.

apiVersion: v1
kind: Secret
metadata:
  name: myapp-secret-environment-variables-v2
type: Opaque
stringData:
  FOO: sample value
  BAR: OTHER SAMPLE VALUE NOW UPPERCASE
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: myapp-container
          image: gcr.io/myapp:1.0.0
          envFrom:
            - secretRef:
                name: myapp-secret-environment-variables-v2

We usually manage this process with a “release number” (based on Twelve-Factor App fifth factor) inside our Infrastructure as Code setup to avoid these manual operations 😉