ConfigMaps & Secrets

ConfigMaps & Secrets in DevOps Tools: --- On the floor of a machine shop, a single milling machine runs a dozen different jobs in a week.


The Analogy: The Machine-Shop Workstation and Its Setup Sheet

On the floor of a machine shop, a single milling machine runs a dozen different jobs in a week. The machine itself never changes, but every job needs its own numbers: spindle speed, feed rate, the part number of the blank to load, which coolant to run. None of that is welded into the machine. It lives on a setup sheet clipped to a board beside the workstation, and when the next job comes up the operator swaps the sheet, not the machine. Separating the settings from the machine is what lets one expensive, tested machine serve every job on the floor -- exactly the reason you never bake a database hostname or a feature flag into a container image.

Two kinds of information hang by that workstation, and they are handled very differently. The setup sheet is open: speeds, feeds, tolerances, anyone walking past can read it, and it is meant to be read. The other kind lives in the controlled tool crib -- the calibrated gauge, the proprietary cutter -- drawn only against a signed chit sealed with a strip of tamper tape. The tape is not a lock. Anyone can peel it and read what is inside; its only job is to keep casual eyes off and to show whether someone already looked. That distinction is the whole difference between a ConfigMap and a Secret, and the tamper tape is base64: it obscures, it does not protect.

How the operator consumes the sheet matters as much as what is on it. Most operators copy the numbers onto their own job traveler once, at the start of the run, and work from that transcription for the next two hours; they do not glance back at the board between parts. A few keep the board in view and read the torque figure fresh for every part. The first way is faster and is how almost every workstation actually runs -- but it means the traveler is a snapshot, frozen at the moment the run began, and the board and the traveler can quietly disagree.

The failure arrives the afternoon a supervisor corrects the setup sheet -- a new, tighter torque spec -- and pins the new sheet expecting the floor to comply at once. The board now shows the correct number, so from the office the change looks done. But every machine already mid-run works from a traveler transcribed that morning, and it keeps torquing to the old figure until the run ends and the operator transcribes again. Parts come off out of spec for the rest of the shift, and nobody notices, because the thing everyone checks -- the pinned sheet -- was updated correctly. The gap is not the sheet; it is that changing the sheet was never the same act as re-reading it.


Syntax or Core Structure

A ConfigMap and a Secret are both just maps of key to value. The one structural difference is that a Secret's values are stored base64-encoded and the object is typed Secret so the cluster treats it with a little more care. A pod never reads these objects directly; it declares which keys it wants and how they should arrive -- as individual environment variables, as a whole block via envFrom, or as files on a mounted volume.

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_ENV: "production"
  LOG_LEVEL: "info"
  MAX_POOL_SIZE: "20"

The Secret looks almost identical, but its one value is the base64 form of the password S3cr3t-P@ss. Storing it base64 is what lets awkward or binary values ride safely inside YAML; it is emphatically not what keeps it safe.

apiVersion: v1
kind: Secret
metadata:
  name: db-credentials
type: Opaque
data:
  DB_PASSWORD: "UzNjcjN0LVBAc3M="

The pod pulls the whole ConfigMap in with envFrom and the single Secret key in explicitly, base64-decoded on the way into the container:

containers:
- name: app
  image: my-app:1.4
  envFrom:
    - configMapRef:
        name: app-config
  env:
    - name: DB_PASSWORD
      valueFrom:
        secretKeyRef:
          name: db-credentials
          key: DB_PASSWORD

To see the environment the container actually ends up with, resolve it the way the kubelet does -- copy every ConfigMap key in, then add the explicitly named Secret key, decoded:

import base64
CONFIGMAP = {'APP_ENV': 'production', 'LOG_LEVEL': 'info', 'MAX_POOL_SIZE': '20'}
SECRET = {'DB_PASSWORD': base64.b64encode(b'S3cr3t-P@ss').decode()}

def resolve_env(configmap, secret):
    env = {}
    for k, v in configmap.items():          # envFrom: every ConfigMap key
        env[k] = v
    env['DB_PASSWORD'] = base64.b64decode(secret['DB_PASSWORD']).decode()
    return env

env = resolve_env(CONFIGMAP, SECRET)
print('resolved pod environment (%d vars):' % len(env))
for k in sorted(env):
    print('%s=%s' % (k, env[k]))

Output:

resolved pod environment (4 vars):
APP_ENV=production
DB_PASSWORD=S3cr3t-P@ss
LOG_LEVEL=info
MAX_POOL_SIZE=20

The container sees four ordinary environment variables. Three arrived as a block from the ConfigMap and one was named explicitly and decoded from the Secret; by the time the process reads them they are indistinguishable strings. That is the point of injection: the application asks its environment for DB_PASSWORD and never learns whether it came from a ConfigMap, a Secret, or a hardcoded default.


Technical Depth: How Values Reach a Container, and Why base64 Is Not a Lock

Three ways in, with one decisive difference

There are three common ways to get a ConfigMap or Secret value into a pod, and they differ most in what happens after you change the source object.

Injection methodGranularityUpdate reaches a running podTypical use
env valueFrom keyRefone named keyno, snapshot at starta single credential or setting
envFromevery key in the objectno, snapshot at startbulk application config
volume mountevery key, as filesyes, after a sync delayconfig a process re-reads live

The first two turn the value into an environment variable, and a process's environment is fixed the moment it starts -- editing the ConfigMap afterward changes nothing already running. A mounted volume behaves differently: the kubelet refreshes the files after a short delay, so a process that re-reads the file can pick up the new value without a restart. Neither is universally correct; the mistake is not knowing which one you chose.

base64 obscures, it does not encrypt

The value stored under a Secret is base64, and it is worth proving to yourself how little that protects. Encoding and decoding need no key at all:

import base64
password = 'S3cr3t-P@ss'
encoded = base64.b64encode(password.encode()).decode()
decoded = base64.b64decode(encoded).decode()
print('plaintext:  %s' % password)
print('base64:     %s' % encoded)
print('decoded:    %s' % decoded)
print('round-trips with no key: %s' % (decoded == password))
print('base64 is encryption: %s' % False)

Output:

plaintext:  S3cr3t-P@ss
base64:     UzNjcjN0LVBAc3M=
decoded:    S3cr3t-P@ss
round-trips with no key: True
base64 is encryption: False

Anyone who can read the Secret object -- through the API, from an etcd backup, in a leaked manifest -- recovers the plaintext with one function call and no key. That is why a Secret is only the first step: you enable encryption at rest for etcd, restrict who can read Secret objects with RBAC, and for anything that truly matters pull the value from an external store like AWS Secrets Manager or Vault at pod start rather than committing even the base64 to a repository.


Real World Example: The Config That Looked Applied

A team runs four replicas that read a FEATURE_TIMEOUT from a ConfigMap, injected as an environment variable. To raise the timeout they edit the ConfigMap from 30 to 60 and run kubectl apply, which reports success. Their deploy tool watches the ConfigMap's resource version, sees it advance, and marks the config rollout complete. The dashboards stay green. Here is what the fleet is actually serving:

STARTED_WITH, DESIRED = '30', '60'

class Pod:
    def __init__(self, name, env_snapshot):
        self.name = name
        self.env = env_snapshot            # captured once, at container start

pods = [Pod('web-%d' % i, {'FEATURE_TIMEOUT': STARTED_WITH}) for i in range(1, 5)]
configmap = {'FEATURE_TIMEOUT': STARTED_WITH}

configmap['FEATURE_TIMEOUT'] = DESIRED     # operator edits and applies
configmap_version = 2

def naive_complete(version):
    return version == 2                    # trusts that apply == rolled out

serving = [p.name for p in pods if p.env['FEATURE_TIMEOUT'] == DESIRED]
stale   = [p.name for p in pods if p.env['FEATURE_TIMEOUT'] != DESIRED]
print('configmap now: FEATURE_TIMEOUT=%s (version %d)' % (configmap['FEATURE_TIMEOUT'], configmap_version))
print('kubectl apply reported: configured')
print('pods serving desired (%s): %d' % (DESIRED, len(serving)))
print('pods still serving old (%s): %d -> %s' % (STARTED_WITH, len(stale), ', '.join(stale)))
print('naive tool says complete: %s' % naive_complete(configmap_version))
print('actually complete: %s' % (len(serving) == len(pods)))
print('stale fraction: %d/%d' % (len(stale), len(pods)))

def restart(old, cm):                      # a rolling restart re-creates pods
    return [Pod(p.name, {'FEATURE_TIMEOUT': cm['FEATURE_TIMEOUT']}) for p in old]

fresh = restart(pods, configmap)
serving2 = [p.name for p in fresh if p.env['FEATURE_TIMEOUT'] == DESIRED]
print('after rollout restart: pods serving desired: %d/%d' % (len(serving2), len(fresh)))

Output:

configmap now: FEATURE_TIMEOUT=60 (version 2)
kubectl apply reported: configured
pods serving desired (60): 0
pods still serving old (30): 4 -> web-1, web-2, web-3, web-4
naive tool says complete: True
actually complete: False
stale fraction: 4/4
after rollout restart: pods serving desired: 4/4

The ConfigMap genuinely holds 60 and its version genuinely advanced, so every signal the tool inspects says the rollout is done. Yet all four running pods captured FEATURE_TIMEOUT as 30 at container start and hold environment variables no ConfigMap edit can reach; the entire fleet serves the old value. The moment a rolling restart re-creates the pods they read the ConfigMap afresh and all four serve 60 -- which is both the fix and the proof that the change never propagated on its own.

The design flaw is in naive_complete: it equates "the ConfigMap was applied" with "every pod serves the new value," when for env-injected config those are separate events divided by a pod restart that nobody triggered. The function reads the resource version and never inspects a single pod, so it reports complete while every request is served with stale config. A correct tool would either mount the ConfigMap as a volume for values meant to change live, or, for env injection, roll the Deployment on change -- commonly by stamping a hash of the ConfigMap into the pod template annotations so the edit itself forces new pods.

The model has real limits. It treats a restart as instantaneous and lossless, when a genuine rolling restart takes time and briefly runs a mix of old and new pods; it ignores that volume-mounted updates arrive only after a kubelet sync delay and still need the process to re-read the file; and it says nothing about ordering, where a pod that restarts for an unrelated reason picks up the new value early and drifts from its siblings. The core lesson survives all of them: with environment injection, editing the source is not the same as rolling it out.


Common Mistakes

  1. Treating a Secret as encrypted because it is base64. base64 is reversible with no key, as the output above shows. Anyone who can read the object or an etcd backup reads the plaintext; you still need encryption at rest and tight RBAC.
  1. Expecting a ConfigMap edit to reach running pods. Values injected as environment variables are a snapshot taken at container start. Editing the ConfigMap changes nothing already running until the pods are restarted.
  1. Committing Secret manifests to Git. The base64 in a Secret manifest is plaintext for practical purposes. Committing it puts the credential in your history forever; use a sealed-secrets tool or an external store instead.
  1. Putting sensitive values in a ConfigMap. ConfigMaps are not treated as sensitive, so they are easier to read and more likely to be logged or dumped. Passwords, tokens, and keys belong in a Secret at minimum.
  1. Using envFrom without knowing the keys. envFrom injects every key in the object as an environment variable, so a stray key can silently shadow or collide with a variable your application already relies on.
  1. Assuming volume-mounted config updates instantly. The kubelet refreshes mounted keys only after a sync delay, and the running process must actually re-read the file. Neither step is immediate, and many processes read config once at startup.
  1. Storing large blobs in a ConfigMap. A ConfigMap lives in etcd and is capped around one megabyte. Configuration files are fine; build artifacts and datasets are not.
  1. Forgetting that env var names must be valid identifiers. A ConfigMap key like app.properties works as a mounted filename but cannot become an environment variable name, so envFrom will skip or reject it.
  1. Sharing one Secret across unrelated apps. Coupling every service to a single Secret means one rotation forces every consumer to restart at once and widens the blast radius of a leak. Scope each Secret to the workload that needs it.

Best Practices

  • Keep configuration out of the image. Bake nothing environment-specific into the container; inject it at runtime through ConfigMaps and Secrets so one image promotes unchanged across dev, staging, and production.
  • Use Secrets for anything sensitive and enable encryption at rest. base64 is not protection; turn on etcd encryption and restrict who can read Secret objects through RBAC.
  • Mount config you want to update live as a volume, not as env vars. A volume-mounted key can be refreshed in place; an env var is frozen at container start and needs a restart to change.
  • Roll pods deliberately after a config change. Trigger a rollout restart or bump a checksum annotation so every pod re-reads the new values, and confirm the fleet actually rolled rather than trusting that apply succeeded.
  • Scope each object to one workload. Give each application its own ConfigMap and Secret so rotations and edits have a small, predictable blast radius.
  • Validate keys before shipping. Make sure keys used as env var names are valid identifiers and that envFrom will not collide with variables your app already sets.
  • Store Secrets outside Git. Use an external secret manager or a sealed-secrets controller so plaintext never lands in version history.
  • Version and label your config objects. Name or annotate ConfigMaps and Secrets with a version so a bad change can be rolled back and a running pod can be traced to the exact config it loaded.

Practice Exercises

  1. Create a ConfigMap with three keys and a pod that consumes all three via envFrom, then exec into the pod and print the environment to confirm every key arrived. Add a fourth key to the ConfigMap, re-check the environment, and explain why the new key is absent until you restart the pod.
  1. Create a Secret holding a database password, decode it by hand with base64 to prove it is not encrypted, then add an RBAC rule so a limited service account cannot read it while your own account still can.
  1. Mount a ConfigMap as a volume and run a small script that re-reads the file every few seconds. Edit the ConfigMap and measure how long the mounted file takes to change, then repeat with the value injected as an env var and observe that it never changes without a restart.
  1. Build a deliberate collision: define the same variable name in a ConfigMap consumed by envFrom and in an explicit env entry, deploy the pod, and determine which value wins. Then reproduce the staleness flaw from the Real World Example and fix it with a rollout restart.