How to use ConfigMap on Kubernetes

2 min read | by Jordi Prats

A ConfigMap an object intended to store configuration for other objects to use. To create a config map we just need to add the data we want to store on the configmap as keys on the data section:

apiVersion: v1
kind: ConfigMap
metadata:
  name: demo-configmap
data:
  file1.txt: |
    this is an example

  file2.txt: |
    this is another example

To be able to use this ConfigMap we will need to mount it to a Pod as a volume. To do so we'll need to declare it as a volume and then use volumeMounts to mount it on the container:

apiVersion: v1
kind: Pod
metadata:
  name: configmapdemo
spec:
  volumes:
  - name: cmdata
    configMap:
        name: demo-configmap
  containers:
  - image: busybox
    command: [ "sleep", "24h" ]
    name: demo
    volumeMounts:
    - name: cmdata
      mountPath: /configmap

Once we apply this Pod and ConfigMap to the cluster:

$ kubectl apply -f .
configmap/demo-configmap created
pod/configmapdemo created

We can check that we can access the ConfigMap data as files using kubectl exec:

$ kubectl exec -it configmapdemo -- ls /configmap
file1.txt  file2.txt
$ kubectl exec -it configmapdemo -- cat /configmap/file1.txt
this is an example
$ kubectl exec -it configmapdemo -- cat /configmap/file2.txt
this is another example

Posted on 28/06/2021

Categories