ConfigMap and Secret
- Docker & Kubernetes course
- Intermediate
- Lesson 70/82
- 4 min
Write a ConfigMap and Secret for app configuration.
ConfigMap and Secret
Settings are split in two: non-secret ones go in a ConfigMap (under version control), secret ones in a Secret (by command, outside the repository). The API's connection address uses the service names:
# 40-ayar.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: api-ayar
namespace: magaza
data:
DB_HOST: db
DB_PORT: "5432"
DB_NAME: magaza
LOG_LEVEL: infoWhen settings change
When the ConfigMap is updated, the API pods using it as environment variables keep seeing the old value. To apply it, the deployment is restarted; since it's renewed gradually, there's no downtime:
kubectl apply -f k8s/40-ayar.yaml
kubectl rollout restart deployment/api -n magaza
kubectl rollout status deployment/api -n magaza
kubectl exec -n magaza deploy/api -- printenv LOG_LEVELPractice The project's ConfigMap
Write a ConfigMap YAML: name api-ayar, namespace magaza; under data, DB_HOST: db, DB_PORT: "5432", LOG_LEVEL: info.
Starter code
# buraya yazSample solution
apiVersion: v1
kind: ConfigMap
metadata:
name: api-ayar
namespace: magaza
data:
DB_HOST: db
DB_PORT: "5432"
LOG_LEVEL: infoExpected output
configmap/api-ayar created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is the DB_PORT value written in quotes?
- ConfigMap values must be strings; 5432 is read as a number in YAML Correct answer
- Because the port is secret
- Quotes aren't required, just habit
- For base64
Explanation: An unquoted number makes the ConfigMap get rejected.
2 Print a single environment variable in the container.
kubectl exec -n magaza deploy/api -- ____ LOG_LEVEL
kubectl exec -n magaza deploy/api -- printenv LOG_LEVEL
Explanation: printenv NAME prints a single variable.
3 Match.
| Term | Meaning |
|---|---|
ConfigMap |
In the repo, not secret |
Secret |
By command, secret |
DB_HOST: db |
Service name |
rollout restart |
Apply the new setting |