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
apiVersion: v1kind: ConfigMapmetadata:name: example-configdata:# property-like keys; each key maps to a simple value"license": "XXXX""licensedto": "dummy"# file-like keysapp.properties: |key1=value1key2=value2
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
ConfigMapsas 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: v1kind: Podmetadata:name: configmap-example-podspec:containers:- name: example-containerimage: alpinecommand: ["sleep", "3600"]env:# Define the environment variable- name: LICENSE # Environment Variable name, can be different from configmap keyvalueFrom:configMapKeyRef:name: example-config # The ConfigMap this value comes from.key: license # The key to fetch.
Explanation
Line 10: We declare that the following lines in
specwill set the environment of the container.Line 12: We declare the name of the environment variable.
Line 14: We tell Kubernetes that the value of the environment variable is coming from the
ConfigMapkey.Line 15: We provide the name of the
ConfigMapdeclared in the previous example.Line 16: We declare the key whose value is to be assigned to the environment variable.
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: v1kind: Podmetadata:name: configmap-demo-podspec:containers:- name: demoimage: alpinecommand: ["sleep", "3600"]volumeMounts:- name: configmountPath: "/config"readOnly: truevolumes:- name: configconfigMap:name: example-config
Explanation
Volumes are set at the pod level, then mounted into containers inside that pod.
Line 15: We provide the name of the
configvolume.Line 17: We assign the name of the
ConfigMapthat has to be mounted.
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
ConfigMapis marked asimmutable.
Free Resources
- undefined by undefined