How to get environment variable in configMap

9/29/2020

I am looking for a way to get environment variable in data section of configmap. In the below yml configuration, I have assigned $NODE_NAME which didn't help me. Is there any way to get this work

apiVersion: v1
kind: ConfigMap
metadata:
  name: config
  namespace: kube-system
data:
  test.conf: |
    {
        "push": 5,
        "test": $NODE_NAME
    }
-- JibinNajeeb
kubernetes

2 Answers

9/29/2020

One way to achieve this would be by using the envsubst as following:

$ export NODE_NAME=my-node-name
$ cat << EOF | envsubst | kubectl apply -f-
apiVersion: v1
kind: ConfigMap
metadata:
  name: config
  namespace: kube-system
data:
  test.conf: |
    {
        "push": 5,
        "test": $NODE_NAME
    }
EOF

But sth tells me that you want to use this in a pod and populate config with environment variable.

Have a look at this example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: config
  namespace: kube-system
data:
  test.conf: |
    {
        "push": 5,
        "test": $NODE_NAME
    }

---
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: example-pod
  name: example-pod
spec:
  initContainers:
  - args:
    - sh
    - -c
    - cat /test.conf | envsubst > /data/test.conf
    image: bhgedigital/envsubst
    name: envsubst
    env:
      - name: NODE_NAME
        valueFrom:
          fieldRef:
            fieldPath: spec.nodeName
    volumeMounts:
    - mountPath: /data
      name: data-volume
    - mountPath: /test.conf
      subPath: test.conf
      name: config-volume
  containers:
  - image: busybox
    name: busybox
    args:
    - sleep 
    - "1000"
    volumeMounts:
    - mountPath: /data
      name: data-volume 
  volumes:
  - name: data-volume
    emptyDir: {}
  - name: config-volume
    configMap:
      name: config

when you apply the above yaml you can check if the file was substituted correctly as following:

$ kubectl exec -it example-pod -- cat /data/test.conf                      
{
    "push": 5,
    "test": minikube
}

As you can see I was testing it in minikube (hence nodeName = minikube in my case)

-- Matt
Source: StackOverflow

9/29/2020

I don't think it's possible to do in any way that you get out of the box. ConfigMap is just injected into your Pod as it is.

What you can do though is to create an Init Container with a custom script to modify the file injected from ConfigMap. In your script you can use sed or envsubst tools.

-- RafaƂ Leszko
Source: StackOverflow