Skip to content
Visual explainer 2h to learn 3 steps

ConfigMaps & Secrets

Inject configuration as env vars and mounted files.

By Invicly Tech, , in Kubernetes Administrator (CKA). About 10 minutes to read.

Topic 13 of 33

In short

ConfigMaps hold non-sensitive configuration and Secrets hold sensitive values like passwords and tokens. Both can be injected as environment variables or mounted as files. Secret values are only base64 encoded by default, so protect them with RBAC and encryption at rest.

Explained simply

Apps need settings: a database address, a log level, a password. You could bake them into the image, but then you would need a new image for every environment. Kubernetes keeps settings outside the image in two objects: ConfigMaps for normal settings and Secrets for sensitive ones.

Your Pod can read these settings in two ways. As environment variables, which the app reads once when it starts. Or as files in a folder, which is better for whole config files and certificates.

A Secret is not a safe. Its values are only base64 encoded, which anyone can decode in one command. What protects a Secret is who may read it (RBAC rules) and whether the cluster encrypts it on disk. Treat Secret YAML like a password file.

Both objects live in a namespace and only Pods in the same namespace can use them. If a Pod refers to a ConfigMap or key that does not exist, it will not start, and kubectl describe tells you exactly which one is missing.

Press Play on a diagram to walk through it one step at a time.

CompareEnv vars vs mounted files
Environment variables
  • env or envFrom in the container
  • Read once at start
  • Changes need a Pod restart
  • Simple key-value settings
Volume files
  • One file per key
  • Updated automatically after a delay
  • Not updated when using subPath
  • Good for config files and certs
MapWhere a setting can come from
Container settings
  • env
    • value: literal
    • configMapKeyRef: one key
    • secretKeyRef: one key
    • fieldRef: Pod name, namespace, IP
  • envFrom
    • configMapRef: all keys
    • secretRef: all keys
    • Optional prefix
  • volumes
    • configMap: one file per key
    • secret: files in tmpfs
    • projected: several sources in one folder

In depth

Four ways to create them

kubectl create configmap and kubectl create secret generic accept the same sources. --from-literal=KEY=value adds one key. --from-file=path adds one key named after the file, with the file content as the value; --from-file=custom=path renames the key. --from-file=dir/ adds one key per file. --from-env-file=app.env reads KEY=value lines.

Secrets also have typed helpers. kubectl create secret tls NAME --cert=tls.crt --key=tls.key creates a kubernetes.io/tls Secret with keys tls.crt and tls.key, which Ingress expects. kubectl create secret docker-registry NAME --docker-server --docker-username --docker-password creates a pull secret for imagePullSecrets. In YAML you can write plain text under stringData and the API server stores it base64 encoded under data.

  • ConfigMaps and Secrets are limited to 1 MiB each
  • Decode a value: kubectl get secret db -o jsonpath='{.data.PASS}' | base64 -d
  • Generic Secrets have type Opaque

Env vars versus mounted files under the hood

Environment variables are copied into the container once, when it starts. Changing the ConfigMap later has no effect until the Pod is recreated, for example with kubectl rollout restart. A referenced key that is missing leaves the container in CreateContainerConfigError, unless you mark the reference optional: true.

Mounted volumes work differently. The kubelet writes each key as a file and later refreshes it when the object changes, usually within a minute or two, through an atomic symlink swap. Secret volumes are stored in tmpfs (memory) on the node, never on its disk. Two exceptions catch people: a file mounted with subPath never updates, and an object marked immutable: true can never be changed, only deleted and recreated.

FlowHow an edited ConfigMap reaches a mounted file
  1. 1
    kubectl edit cm

    New data saved in etcd

  2. 2
    kubelet notices

    On its periodic sync, using its cache

  3. 3
    Writes new files

    Into a fresh hidden folder

  4. 4
    Swaps a symlink

    All keys change at once

  5. 5
    App rereads

    Only if the app watches or reloads

Choosing keys, paths and permissions

A configMap or secret volume normally creates one file per key. Use items to pick only some keys and give them custom file names, and defaultMode to set permissions; the default is 0644. A Secret holding a private key should usually use defaultMode 0400.

Mounting a volume at a path hides whatever the image already had in that folder. To drop a single file into an existing folder such as /etc/nginx/conf.d, mount with subPath, and accept that it will not auto-update. envFrom can add a prefix to every imported key, which avoids clashes when you import from two sources.

  • items: [{ key: nginx.conf, path: default.conf }]
  • defaultMode: 0400 for private keys
  • envFrom: [{ prefix: DB_, secretRef: { name: db } }]

Encrypting Secrets at rest

By default the API server writes Secrets to etcd as plain bytes, so anyone with an etcd backup can read them. To fix this, write an EncryptionConfiguration file listing a provider such as aescbc, aesgcm, secretbox or kms (v2), followed by identity, and point the API server at it with --encryption-provider-config. On kubeadm clusters you add that flag and a volume mount to /etc/kubernetes/manifests/kube-apiserver.yaml.

Only new writes are encrypted. Rewrite existing Secrets with kubectl get secrets -A -o json | kubectl replace -f -. You can confirm by reading the raw key with etcdctl get /registry/secrets/NAMESPACE/NAME: encrypted values start with a prefix like k8s:enc:aescbc:v1:.

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Create ConfigMaps and Secrets~40m
  2. 2
    Inject them as environment variables~40m
  3. 3
    Mount them as files~40m

Key points

  • kubectl create secret generic encodes values to base64 for you.
  • Base64 is encoding, not encryption; enable EncryptionConfiguration for etcd.
  • A Pod stays in CreateContainerConfigError if a referenced key is missing.
  • ConfigMaps and Secrets must be in the same namespace as the Pod.

Key terms

Tap a card to flip it. 0/5 known

Examples

yaml
# kubectl create configmap app --from-literal=MODE=prod
# kubectl create secret generic db --from-literal=PASS=s3cret
spec:
  containers:
    - name: app
      image: busybox:1.36
      command: ["sh", "-c", "env; sleep 3600"]
      envFrom:
        - configMapRef: { name: app }
      env:
        - name: DB_PASS
          valueFrom: { secretKeyRef: { name: db, key: PASS } }
      volumeMounts: [{ name: cfg, mountPath: /etc/app }]
  volumes: [{ name: cfg, configMap: { name: app } }]

Ship an nginx config file from a ConfigMap

You want nginx to use your own server block without building an image. Step 1: create a ConfigMap from the file; the key becomes default.conf. Step 2: mount it at /etc/nginx/conf.d, which replaces that folder's contents. Step 3: check the file inside the Pod. Step 4: after editing the ConfigMap, the file updates on its own, but nginx needs a reload or a rollout restart to use it.

bash
kubectl create configmap nginx-conf --from-file=default.conf
kubectl create deployment web --image=nginx:1.27 --dry-run=client -o yaml > web.yaml
# in web.yaml, under the container:
#   volumeMounts: [{ name: conf, mountPath: /etc/nginx/conf.d }]
# under spec (Pod level):
#   volumes: [{ name: conf, configMap: { name: nginx-conf } }]
kubectl apply -f web.yaml
kubectl exec deploy/web -- cat /etc/nginx/conf.d/default.conf
kubectl rollout restart deployment/web   # after editing the ConfigMap

A Pod stuck in CreateContainerConfigError

A new Pod never starts. Step 1: kubectl get pod shows CreateContainerConfigError. Step 2: describe shows the event: secret "db-creds" not found, or couldn't find key PASSWORD. Step 3: compare with what exists in that namespace; often the Secret was created in default instead. Step 4: create it in the right namespace. The kubelet retries on its own, so the Pod starts without being deleted.

bash
kubectl -n shop get pod api-0
kubectl -n shop describe pod api-0 | grep -A5 Events
kubectl get secret -A | grep db-creds        # found in default!
kubectl -n shop create secret generic db-creds --from-literal=PASSWORD=s3cret
kubectl -n shop get pod api-0 -w

Quick reference

  • kubectl create cm app --from-file=app.properties --from-literal=MODE=prod
  • kubectl create secret tls web-tls --cert=tls.crt --key=tls.key
  • kubectl get secret db -o jsonpath='{.data.PASS}' | base64 -d
  • echo -n 's3cret' | base64 (use -n, or a newline sneaks into the value)
  • Env vars never refresh; mounted files do, except with subPath
  • immutable: true cannot be undone; delete and recreate instead
  • Encryption at rest: --encryption-provider-config on kube-apiserver

Common mistakes

  • Committing Secret YAML to Git thinking base64 hides the value.
  • Expecting env vars to update after editing the ConfigMap.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1You edit a ConfigMap that a running Pod uses through envFrom. When does the app see the new value?

Question 2

2Which command creates a Secret that an Ingress can use for HTTPS?

Question 3

3A Secret mounted with subPath is updated. What does the container see?

Question 4

4After enabling encryption at rest, how do you encrypt Secrets that already existed?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a Secret named api-key with key TOKEN=abc123 and print the decoded value back.

  2. Exercise 2medium

    Run a busybox Pod that gets LOG_LEVEL from ConfigMap app (key level) as an env var and mounts Secret api-key read-only at /etc/secret with mode 0400.

  3. Exercise 3hard

    On a kubeadm lab, enable aescbc encryption at rest for Secrets and prove a new Secret is encrypted in etcd.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Are Kubernetes Secrets secure?
Only as secure as your setup. By default they are base64 encoded, not encrypted, so you need RBAC that limits who can read them and encryption at rest for etcd. Many teams add an external secret store on top.
Why does my Pod not see the updated ConfigMap?
If you used environment variables, the Pod must be recreated. If you used a volume, wait a minute or two, check you are not using subPath, and make sure the app rereads the file.
What is the difference between data and stringData in a Secret?
data holds base64 encoded values. stringData lets you write plain text, which the API server encodes and merges into data when it saves the Secret.

Go deeper

ShareXLinkedInWhatsApp