Kubernetes - ConfigMap

Kubernetes ConfigMap

Problem with setting the configuration in the deployment file is tight coupling between application and configuration. ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable. ConfigMaps can be generated from Files, Literals or Environment Files

Create ConfigMap from Literal

1
kubectl create configmap app-config --from-literal=FOO=bar --from-literal=BAZ=qux

Use kubectl describe cm app-config to view the config map. Use kubectl describe cm app-config command to describe the config map.

1
kubectl describe cm app-config

Create ConfigMap from File

When you create a ConfigMap using –from-file, the filename becomes a key stored in the data section of the ConfigMap. The file contents become the key’s value.

1
2
3
$ echo -n bar > ./FOO
$ echo -n qux > ./BAZ
$ kubectl create configmap app-config --from-file=./FOO --from-file=./BAZ

Create ConfigMap from Env File

1
2
3
4
5
6
$ cat << EOF > env
FOO=bar
BAZ=qux
EOF

kubectl create configmap app-config --from-env-file=env

Create ConfigMap using YAML file

app-configmap.yaml

1
2
3
4
5
6
7
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
FOO: bar
BAZ: qux

Using ConfigMap as Environment Variable

busybox-configmap.yaml - set environment variable for a pod using configmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
apiVersion: v1
kind: Pod
metadata:
name: busybox
labels:
name: busybox
spec:
restartPolicy: OnFailure
containers:
- name: busybox
image: busybox
command: [ "/bin/sh", "-c", "env" ]
env:
- name: FOO
valueFrom:
configMapKeyRef:
name: app-config
key: FOO

after the pod is created, use kubectl logs busybox to check the pod’s log. FOO environment variable is set with value “bar”.

Add ConfigMap data to a Volume

You can add ConfigMap to a container as a volume

pod-configmap-volume.yml

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-volume-test
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
command: [ "/bin/sh", "-c", "cat /etc/config/Foo;" ]
volumeMounts:
- name: config-volume
mountPath: /etc/config
volumes:
- name: config-volume
configMap:
# Provide the name of the ConfigMap containing the files you want
# to add to the container
name: app-config
items:
- key: FOO
path: Foo
- key: BAZ
path: Baz
restartPolicy: Never

When the pod runs, file /etc/config/Foo is displayed. it contains the value for key FOO. Value is ‘bar’

References