CodeBlanks Logo Icon CodeBlanks

Environment variable

Learn to mount a ConfigMap as environment variables.

As environment variables

ConfigMap values are given to a container as environment variables in two ways: one at a time with valueFrom.configMapKeyRef, or all keys at once with envFrom:

      containers:
        - name: api
          image: api:1.0
          envFrom:
            - configMapRef:
                name: api-ayar
          env:
            - name: SEVIYE
              valueFrom:
                configMapKeyRef:
                  name: api-ayar
                  key: LOG_LEVEL

Errors and optionality

If the ConfigMap a pod uses doesn't exist, the container stays in CreateContainerConfigError. If it's allowed to be missing, optional: true is written:

$ kubectl get pod api-5d8f7c9b4-qrstu
NAME                  READY   STATUS                       RESTARTS
api-5d8f7c9b4-qrstu   0/1     CreateContainerConfigError   0
$ kubectl describe pod api-5d8f7c9b4-qrstu | grep -i configmap
  Warning  Failed  configmap "api-ayar" not found

Practice Give the config to the container

Write a Deployment's container section (starting with containers:): container named api, image api:1.0; all keys of the api-ayar ConfigMap with envFrom; under env, the SEVIYE variable from the LOG_LEVEL key of api-ayar with configMapKeyRef.

Starter code

terminal
# buraya yaz

Sample solution

terminal
containers:
  - name: api
    image: api:1.0
    envFrom:
      - configMapRef:
          name: api-ayar
    env:
      - name: SEVIYE
        valueFrom:
          configMapKeyRef:
            name: api-ayar
            key: LOG_LEVEL

Expected output

deployment.apps/api configured
$ kubectl exec deploy/api -- env | grep -E "LOG_LEVEL|SEVIYE"
LOG_LEVEL=info
SEVIYE=info

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When a value in the ConfigMap changes, what does a running pod using it as an environment variable see?

  • The pod crashes
  • The old value; it doesn't change until the pod restarts Correct answer
  • The new value immediately
  • An empty value

Explanation: Environment variables are read when the process starts; kubectl rollout restart is needed.

2 Make all keys of the ConfigMap environment variables.

Question
          ____:
            - configMapRef:
                name: api-ayar
Answer
          envFrom:
            - configMapRef:
                name: api-ayar

Explanation: envFrom loads all keys at once.

3 Match.

Term Meaning
envFrom All keys
configMapKeyRef A single key
CreateContainerConfigError ConfigMap not found
optional: true Fine if missing

All lessons in Intermediate