Sign In

Curriculum 14: ConfigMaps & Secrets

Environment Variables

10 min · 25 XP

Injecting ConfigMaps and Secrets as Environment Variables

Environment variables are the simplest way to pass configuration into containers. Kubernetes lets you inject individual keys or entire ConfigMaps and Secrets as environment variables.

Injecting All Keys with envFrom

Load every key from a ConfigMap or Secret as environment variables:

apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: myapp:1.0
      envFrom:
        - configMapRef:
            name: app-config
        - secretRef:
            name: app-secrets

Each key in app-config becomes an environment variable. If a key exists in both sources, the last one listed wins.

Selecting Individual Keys with valueFrom

Reference specific keys when you need only a subset or want to rename variables:

env:
  - name: DB_HOST
    valueFrom:
      configMapKeyRef:
        name: app-config
        key: DATABASE_HOST
  - name: DB_PASSWORD
    valueFrom:
      secretKeyRef:
        name: db-credentials
        key: password

This gives you explicit control over which keys are exposed and what names they use inside the container.

Optional References

Mark a reference as optional so the pod starts even if the ConfigMap or Secret does not exist:

env:
  - name: FEATURE_FLAG
    valueFrom:
      configMapKeyRef:
        name: feature-flags
        key: enable-beta
        optional: true

Verifying Environment Variables

Check that variables are correctly injected:

kubectl exec my-pod -- env | sort
kubectl exec my-pod -- printenv DB_HOST

Key Differences from Volume Mounts

Environment variables are set once at container startup. Unlike volume mounts, they do not update when the underlying ConfigMap or Secret changes. You must restart the pod (or its owning Deployment) to pick up new values.

Use envFrom for bulk injection when key names already match what your app expects. Use valueFrom when you need to cherry-pick keys or map them to different variable names.