hakk

software development, devops, and other drivel
Tree lined path

Using a Kubernetes Configmap in a Pod

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!”.

Use as Environment Variable

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.

Webapp color webpage in green
Webapp color webpage in green

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.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: webapp-color-cm
data:
  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.

Next create the service and view the resulting page. Hopefully it appears green!

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.