Environment variable
- Docker & Kubernetes course
- Intermediate
- Lesson 45/82
- 4 min
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_LEVELErrors 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 foundPractice 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
# buraya yazSample solution
containers:
- name: api
image: api:1.0
envFrom:
- configMapRef:
name: api-ayar
env:
- name: SEVIYE
valueFrom:
configMapKeyRef:
name: api-ayar
key: LOG_LEVELExpected 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.
____:
- configMapRef:
name: api-ayar
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 |