Browse topics

ConfigMaps

Version
1.37
Review
Draft

Summary#

A ConfigMap stores non-secret configuration as keys and values. A Pod in the same namespace can read it as environment variables, command arguments or files in a volume. Its data is limited to 1 MiB.

Syntax#

sh
kubectl create configmap NAME --from-literal=KEY=VALUE --from-file=FILE
yaml
env:
  - name: APP_MODE
    valueFrom:
      configMapKeyRef:
        name: settings
        key: mode
envFrom:
  - configMapRef:
      name: settings

Example#

sh
(
  set -eu
  ns="ref-configmaps-$$"
  kubectl create namespace "$ns" >/dev/null
  trap 'kubectl delete namespace "$ns" >/dev/null' EXIT
  kubectl wait -n "$ns" --for=create serviceaccount/default --timeout=60s >/dev/null

  kubectl apply -n "$ns" -f - <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: settings
data:
  mode: production
  app.properties: |
    greeting=hello
---
apiVersion: v1
kind: Pod
metadata:
  name: reader
spec:
  restartPolicy: Never
  containers:
    - name: reader
      image: busybox:1.37
      command: ["sh", "-c", "echo \"mode=$APP_MODE\"; cat /etc/app/app.properties"]
      env:
        - name: APP_MODE
          valueFrom:
            configMapKeyRef:
              name: settings
              key: mode
      volumeMounts:
        - name: config
          mountPath: /etc/app
          readOnly: true
  volumes:
    - name: config
      configMap:
        name: settings
EOF
  kubectl wait -n "$ns" --for=jsonpath='{.status.phase}'=Succeeded pod/reader --timeout=120s >/dev/null
  kubectl logs -n "$ns" reader
)

Expected output#

Text
configmap/settings created
pod/reader created
mode=production
greeting=hello

Common mistakes#

Environment variables are read when a container starts, so editing the ConfigMap does not change them; restart the Pods. Mounted files are updated eventually, except through a subPath mount, and the application still has to reload them.

Version applicability#

The example targets Kubernetes 1.37. The immutable: true field is stable since 1.21. Once set, it prevents changes to data and binaryData and cannot be unset. To change the data, create a ConfigMap with a new name and update the Pod template to reference it.

The kubelet rejects ConfigMap references in static Pod manifests. Kubernetes 1.37 removed the PreventStaticPodAPIReferences feature gate that previously allowed an opt-out.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0