replace configmap contents with some environment variables

12/12/2019

i am running a statefulset where i use volumeClaimTemplates. everything's fine there.

i also have a configmap where i would like to essentially replace some entries with the name of the pod for each pod that this config file is projected onto; eg, if the configmap data is:

ThisHost=<hostname -s>
OtherConfig1=1
OtherConfig1=2
...

then for the statefulset pod named mypod-0, the config file should contain ThisHost=mypod-0 and ThisHost=mypod-1 for mypod-1.

how could i do this?

-- yee379
configmap
kubernetes
kubernetes-statefulset

1 Answer

12/12/2019

The hostnames are contained in environment variables within the pod by default called HOSTNAME. It is possible to modify the configmap itself if you first:

  • mount the configmap and set it to ThisHost=hostname -s (this will create a file in the pod's filesystem with that text)
  • pass a substitution command to the pod when starting (something like $ sed 's/hostname/$HOSTNAME/g' -i /path/to/configmapfile)

Basically, you mount the configmap and then replace it with the environment variable information that is available within the pod. It's just a substitution operation.

Look at the example below:

apiVersion: v1
kind: Pod
metadata:
name: command-demo
labels:
purpose: demonstrate-command
spec:
containers:
- name: command-demo-container
image: debian
command: ["sed"]
args: ["'s/hostname/$HOSTNAME'", "-i", "/path/to/config/map/mount/point"]
restartPolicy: OnFailure

The args' syntax might need some adjustments but you get the idea.

Please let me know if that helped.

-- OhHiMark
Source: StackOverflow