ConfigMap

ConfigMap is used to store non-sensitive information as key-value pairs. Pods can consume ConfigMaps via environment variables, command-line arguments, or volume mounts.
ConfigMap decouples environment-specific configuration from your application code, which improves application portability.
Note that ConfigMap does not provide any encryption.

How to Write a ConfigMap Object

Below is an example of a ConfigMap object:

1
2
3
4
5
6
7
8
apiVersion: v1
kind: ConfigMap
metadata:
name: configmap-demo
data:
debug: enable
index.html: |
hello, world

Like every other Kubernetes API object, a ConfigMap has apiVersion, kind, and metadata fields, but it does not have a spec field. ConfigMap provides two fields — data and binaryData — for storing configuration data.
data: Stores configuration data. Values must contain only UTF-8 encoded data; non-UTF-8 data must use binaryData instead.
binaryData: Stores binary data.

There is also an immutable field that specifies whether the data stored in a ConfigMap can be modified.
Note that keys within the same ConfigMap must be unique. A key already used in data cannot be used in binaryData, and vice versa.

How to Use a ConfigMap

Containers in a Pod can consume a ConfigMap in four ways:

  1. As command-line arguments to the container’s entrypoint
  2. As environment variables for the container
  3. As a read-only volume
  4. By reading the ConfigMap directly via the Kubernetes API from within the application

Below is a simple example (also uploaded to GitHub):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
apiVersion: v1
kind: Pod
metadata:
name: configmap-demo-pod
spec:
containers:
- name: demo
image: nginx
env:
# environment for container
- name: DEBUG
valueFrom:
configMapKeyRef:
name: configmap-demo
key: debug
volumeMounts:
# read-only volume
- name: config
mountPath: "/usr/share/nginx/html"
readOnly: true
volumes:
- name: config
configMap:
name: configmap-demo

Results:

  1. Verify the environment variable

env

  1. Verify the read-only file

volume