• +43 660 1453541
  • contact@germaniumhq.com

Configuring Containers via ConfigMaps Volumes in Kubernetes


Configuring Containers via ConfigMaps Volumes in Kubernetes

Kubernetes provides ConfigMap objects that allow storing key value pairs into its own etcd storage. The backup of Kubernetes also includes then those objects. Mounting a single key from the config as a file in a container is also straightforward. We’ll see in this article exactly how.

First we need to create the ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test-config
data:
  custom-config: |
    multi
    line
    config
    file

Then in our deployment specification we need to add the configuration as a volume, and mount a single key using subPath:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: testpod
  labels:
    app: testpod
spec:
  replicas: 1
  selector:
    matchLabels:
      app: testpod
  template:
    metadata:
      labels:
        app: testpod
    spec:
      containers:
      - name: nginx
        image: nginx
        volumeMounts:
        - mountPath: /etc/custom-config
          name: test-config
          subPath: custom-config
      volumes:
      - name: test-config
        configMap:
          name: test-config

We still have now all the files in /etc with our new custom-config addition:

$ kubectl exec -it testpod-75ffff5d9f-x5hw6 ls /etc
...
cron.daily		issue	       pam.d	      shadow-
custom-config		issue.net      passwd	      shells
debconf.conf		kernel	       passwd-	      skel
...

And it has the right content:

$ kubectl exec -it testpod-75ffff5d9f-x5hw6 cat /etc/custom-config
multi
line
config
file

This is great for changing single configuration files from containers, without having to have some funky init containers that makes the copying around: