ConfigMaps in Kubernetes
When you create a pod in Kubernetes, you can set environment variables for the containers that run in the pod. To set environment variables, include the env
or envFrom
field in the configuration file.
There are 3 types of environment variables in Kubernetes.
1: Key-value pair
2: ConfigMaps
3: Secrets
In this article, we’ll focus on ConfigMaps.
ConfigMaps are used to pass configuration data in the form of key-value pairs in Kubernetes.
There is a 2 step process to insert a ConfigMap into a pod when it is created.
The first task is to create the ConfigMap, and the second task is to attach them to the pod.
There are two ways to create a ConfigMap.
1: Imperative way — We pass the configuration details in the command line.
2: Declarative way — We create a configuration file.
Let’s look at the imperative method. We directly pass the details in by using the command line.
The --from-literal
option is used to specify the key-value pairs in the command line. In the above screenshot, we are creating a ConfigMap by the name app-config
with a key-value pair of APP_COLOR=blue
.
If you want to add additional key-value pairs, simply specify the --from-literal
option multiple times.
The other way to insert configuration data is through a file. For this, we just need to create a definition file just like we do for the pod creation file.
This is our ConfigMap file.
Command to execute:
kubectl create -f config-map.yaml
Get config details:
kubectl get configmaps
Describe configmaps
— it shows all the config data details:
kubectl describe configmaps
We have created our config file, now let’s inject it into a pod definition file.
In the above picture, we have injected the metadata name of the config file as configMapRef
in the pod definition file. This is the way, we inject the config data/environment variables into a pod.
Now we can create the pod file as we injected the reference:
kubectl create -f pod-definition file
Always remember ConfigMaps store the data in plain text format. If you want to store sensitive data, please use the “secrets” concept for this.
You can refer to the official documentation for additional details.