Skip to Content

Kubernetes Field Guide · Chapter 6 of 16

ConfigMaps and Secrets

The same image should run in development, staging and production. What changes between them is configuration, and some of it is secret. Learn ConfigMaps and Secrets, what Secrets do not protect you from, and how teams keep real secrets out of Git and out of reach.

  • 30 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Kubernetes in production. Updated .

image web:1.4built onceConfigMapLOG_LEVEL, URLsSecretDB_PASSWORDpodwhat runsweb:1.4env: LOG_LEVEL=infoenv: DB_PASSWORD=•••file: /etc/app/devLOG_LEVEL=debugstagingLOG_LEVEL=infoprodLOG_LEVEL=warn
The chapter in one pictureBuild the image once. Change behaviour per environment with ConfigMaps and Secrets.

By the end you can

0 of 4

ConfigMaps

A ConfigMap holds non-secret configuration as key-value pairs: log levels, feature flags, URLs, or whole config files. Build one image, and give each environment its own ConfigMap.

web-config.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config
data:
  LOG_LEVEL: info
  FEATURE_CHECKOUT_V2: "false"
  nginx.conf: |
    server {
      listen 80;
      location /healthz { return 200 "ok"; }
    }
Values are always strings. Quote booleans and numbers or the apply fails.
A whole file as one value. The | keeps line breaks.

A ConfigMap is limited to 1 MiB. Large files belong in the image or in object storage.

Environment variables or mounted files

deployment.yaml (pod spec)
spec:
  containers:
    - name: app
      image: ghcr.io/example/shop:1.8.0
      envFrom:
        - configMapRef:
            name: web-config
      env:
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: db
              key: DB_PASSWORD
      volumeMounts:
        - name: config
          mountPath: /etc/nginx/conf.d
          readOnly: true
  volumes:
    - name: config
      configMap:
        name: web-config
        items:
          - key: nginx.conf
            path: default.conf
Every key becomes an environment variable.
One key from a Secret, as one variable.
Keys become files. Here nginx.conf is mounted as /etc/nginx/conf.d/default.conf.
Environment variablesMounted files
Best forSimple flags and settingsConfig files, certificates
Picks up changesOnly after a restartEventually, usually within a minute (not with subPath)
RiskLeaks into crash dumps and child processesThe app must notice the file changed

Time to practise. Each value below belongs in exactly one place:

Interactive

Where does this value live? Sort all ten.

Bake into the image

    ConfigMap

      Secret, from a secret manager

        The spec or Helm values in Git

          Secrets are not encrypted

          A Secret looks like a ConfigMap whose values are base64. That is an encoding, so binary data survives YAML. It is not encryption:

          Interactive

          What is actually inside a Secret

          base64:

          Base64 is an encoding, not encryption. Anyone who can read the Secret can read the value.

          What actually protects a Secret:

          • RBAC. Only grant get and list on Secrets to those who need them. list returns every value in the namespace.
          • Who can create pods. Anyone who can create a pod in a namespace can mount any Secret in it and print it. That permission is as sensitive as reading Secrets directly.
          • Encryption at rest. By default Secrets sit in etcd unencrypted. Self-run clusters need an encryption configuration; EKS, AKS and GKE offer envelope encryption with their KMS.

          External secret stores

          The real value should live in a secret manager (AWS Secrets Manager, Vault, Azure Key Vault, GCP Secret Manager) with its own access control, audit log and rotation. The External Secrets Operator copies values into ordinary Kubernetes Secrets, so apps do not change:

          externalsecret.yaml
          apiVersion: external-secrets.io/v1
          kind: ExternalSecret
          metadata:
            name: db
          spec:
            refreshInterval: 1h
            secretStoreRef:
              kind: ClusterSecretStore
              name: aws-secrets-manager
            target:
              name: db
            data:
              - secretKey: DB_PASSWORD
                remoteRef:
                  key: prod/shop/db
                  property: password
          How often to re-read the source. Secret managers bill per API call, so do not poll every few seconds across hundreds of secrets.
          Points at a store configured once with credentials, ideally through workload identity (chapter 11).
          The Kubernetes Secret it creates and keeps in sync.

          Step through it

          A secret from your secret manager to an environment variable

          1. Secret managerAWS, Vault, GCP
          2. External Secretsoperator
          3. Kubernetes Secretdb-credentials
          4. Podenv DB_PASSWORD

          Step 0 of 4

          Press Play, or step through with Next.

          Two other common options: Sealed Secrets and SOPS encrypt values so the encrypted file can be committed to Git and decrypted only inside the cluster.

          Hands-on: config without rebuilding

          Live lab · no install

          Config without rebuilding

          kind-learn
          1. Tasks0/6
          2. Create a ConfigMap and a Secret
            kubectl create configmap demo-config --from-literal=GREETING=hello
            kubectl create secret generic demo-secret --from-literal=API_KEY=dev-123
          3. Run an app that reads both

            cfg-demo.yaml loads every key as an environment variable with envFrom.

            kubectl apply -f cfg-demo.yaml
            kubectl rollout status deployment/cfg-demo
          4. Read what the app sees
            kubectl logs deploy/cfg-demo
          5. Prove a Secret is only base64

            Anyone allowed to get the Secret can read it. Access control is the protection, not the encoding.

            kubectl get secret demo-secret -o jsonpath='{.data.API_KEY}' | base64 -d
          6. Change the greeting

            Update the ConfigMap in place. Then check the logs: has the app noticed?

            kubectl create configmap demo-config --from-literal=GREETING=bonjour --dry-run=client -o yaml | kubectl apply -f -

            The ConfigMap changed, but env vars are read once at start. The running pod still says hello.

          7. Restart to pick it up
            kubectl rollout restart deployment/cfg-demo
            kubectl rollout status deployment/cfg-demo
            kubectl logs deploy/cfg-demo
          8. Lab complete. Keep experimenting, or press Reset to start again.
          ↑↓ history · Tab complete · Ctrl+C stop
          Cluster map live
          • ready
          • starting / not ready
          • failing
          • terminating
          Prefer your own machine? The same steps on a local cluster
          Terminal
          kubectl create configmap demo-config --from-literal=GREETING=hello
          kubectl create secret generic demo-secret --from-literal=API_KEY=dev-123
          

          Save this as cfg-demo.yaml and apply it:

          cfg-demo.yaml
          apiVersion: apps/v1
          kind: Deployment
          metadata:
            name: cfg-demo
          spec:
            replicas: 1
            selector:
              matchLabels:
                app: cfg-demo
            template:
              metadata:
                labels:
                  app: cfg-demo
              spec:
                containers:
                  - name: app
                    image: busybox:1.37
                    command: ["sh", "-c", "echo GREETING=$GREETING API_KEY=$API_KEY; sleep 3600"]
                    envFrom:
                      - configMapRef:
                          name: demo-config
                      - secretRef:
                          name: demo-secret
          Terminal
          kubectl apply -f cfg-demo.yaml
          kubectl logs deploy/cfg-demo
          kubectl get secret demo-secret -o jsonpath='{.data.API_KEY}' | base64 -d
          GREETING=hello API_KEY=dev-123
          dev-123
          logs deploy/...
          Logs from one pod of the Deployment.
          base64 -d
          Proof that anyone allowed to get the Secret can read it.

          Mini mission

          Change config without a new image

          Change GREETING to bonjour and get the running app to print it, without touching the Deployment YAML or the image.

          Reveal one safe solution
          Terminal
          kubectl create configmap demo-config --from-literal=GREETING=bonjour --dry-run=client -o yaml | kubectl apply -f -
          kubectl rollout restart deployment/cfg-demo
          kubectl rollout status deployment/cfg-demo
          kubectl logs deploy/cfg-demo
          

          The --dry-run=client -o yaml | kubectl apply pattern updates an existing object from a create command. The restart is needed because environment variables are read once at start. Clean up with kubectl delete deploy/cfg-demo configmap/demo-config secret/demo-secret.

          Check yourself

          Quiz

          0 of 4 answered

          1. 1. You change a ConfigMap used through envFrom. When do running pods see the new value?
          2. 2. What protects the value inside a Kubernetes Secret by default?
          3. 3. A user cannot get Secrets in a namespace but can create pods there. Can they read a Secret?
          4. 4. Why is committing Secret YAML to Git a problem even in a private repository?

          Further reading