A ConfigMap is provided as a way to inject configuration data into a pod/pods. It can be included as files or be used as environment variables. Below are a couple of examples of mounting a configmap using both methods.
Use as File
In this first example I’ll show how to create a configmap and mount it using the key(s) as filenames and the data as the file content. It will then be used in an Nginx container as the index page.
First create the configmap if the pod is created first it won’t start properly as it wouldn’t be able to find the configmap.
You can check if the configmap is available using kubectl get configmaps. The output should show nginx-cm.
Next create the pod, once it is up and running create the service and view the page in the browser. It should appear plain white with the only words being “Hello, World!”.
Now let’s take a look at using the configmap as environment variables. In this example I’ll use the Kode Kloud webapp color so the value and any changes will be easily visible.
Like last time the first thing to do is create the configmap so it will be available to the pod. To start we’ll use the color green.
# file: webapp-color-cm.yamlapiVersion: v1kind: ConfigMapmetadata:
name: webapp-color-cmdata:
app-color: green
Check if the configmap is available using kubectl get configmaps. The output should show webapp-color-cm.
Next create the pod, I added some comments in the yaml to help point out the configmap mapping and how to choose the environment variable name.
# file: webapp-color-pod.yamlapiVersion: v1kind: Podmetadata:
labels:
run: webapp-colorname: webapp-colorspec:
containers:
- name: test-containerimage: kodekloud/webapp-color:latestimagePullPolicy: IfNotPresentenv:
# the environment variable that will be set - name: APP_COLORvalueFrom:
configMapKeyRef:
# the name of the configmap created previouslyname: webapp-color-cm# the key to use the data from key: app-color
If you would like to change the background color of the page; it’s possible to edit the configmap. You’ll have to recreate the pod(s) for the changes to be picked up though.
kubectl edit configmaps webapp-color-cm
Change ‘green’ to ‘red’ then save and exit the editor.
Finally recreate the pod, you can either delete and then create again or run the following kubectl replace -f webapp-color-pod.yaml --force. Once this finishes and the pod is ready again, refresh the page and the background will now be red.
Originally posted Feb 12, 2024
last updated Jun 5, 2024
by bmcculleyTagged: