What is a ConfigMap in Kubernetes?

Today, in the world of application development, it’s recommended to separate the configuration from the code. Kubernetes’ ConfigMaps helps us do this.

Create a ConfigMap

ConfigMap allows you to define key and values or a properties file that can be used either at startup of the pod, or as a mount on the pod.

apiVersion: v1
kind: ConfigMap
metadata:
name: example-config
data:
   # property-like keys; each key maps to a simple value
"license": "XXXX"
  "licensedto": "dummy"
  # file-like keys
app.properties: |
     key1=value1
key2=value2
view raw cmcreate.yaml hosted with ❤ by GitHub
Create a configmap

Uses of ConfigMap

We can use the ConfigMap for configuration inside a pod in the following ways:

  • Using commands and arguments inside a container.
  • Using environment variables for a container
  • Adding the ConfigMaps as a file in read-only volume, from where the application can read.
  • Using the Kubernetes API in the code running inside the container that can read the configmap.

Example

Here, we load the ConfigMaps values during pod initialization as environment variables.

apiVersion: v1
kind: Pod
metadata:
name: configmap-example-pod
spec:
containers:
name: example-container
image: alpine
command: ["sleep", "3600"]
env:
# Define the environment variable
name: LICENSE # Environment Variable name, can be different from configmap key
valueFrom:
configMapKeyRef:
name: example-config # The ConfigMap this value comes from.
key: license # The key to fetch.
view raw cmload.yaml hosted with ❤ by GitHub
Load the configmap values

Mount ConfigMap as a file in read-only volume

Following is an example of how to use values from a ConfigMap at the time of container initialization:

apiVersion: v1
kind: Pod
metadata:
name: configmap-demo-pod
spec:
containers:
name: demo
image: alpine
command: ["sleep", "3600"]
volumeMounts:
name: config
mountPath: "/config"
readOnly: true
volumes:
name: config
configMap:
name: example-config
view raw mountcm.yaml hosted with ❤ by GitHub
Mount the configmap

Volumes are set at the pod level, then mounted into containers inside that pod. The mounted configuration maps are updated automatically when the value in the `ConfigMap` changes.

Conclusion

ConfigMaps are a great mechanism to set up configurations separate from code. The configurations are updated automatically and redeployment is not required.

Note: The above does not hold true if the ConfigMap is marked as immutable.