Search code examples
kubernetesenvironment-variableskubernetes-helm

Inject host's environment variable into K8s Pod


I would like to run a pod on one of my IoT devices. Each one of those devices contains an environment variable I want this pod to use. Is there any way to inject this env variable into the pod using build-in templating of helm/kubectl? I was trying the following on my deployment.yaml file:

env: 
  - name: XXX
    value: $ENV_FROM_HOST

but when executing the pod and trying the get XXX value, I get the string $ENV_FROM_HOST instead of its value from the host:

$ echo $XXX
$ENV_FROM_HOST

Thanks.


Solution

  • It's not possible to directly pass the host's env vars to the pods. I often do that by creating a ConfigMap.

    1. Create a ConfigMap with from-lireral option:

      kubectl create configmap testcm --from-literal=hostname=$HOSTNAME
      
    2. Refer to that in the Pod's manifest:

      - name: TEST
        valueFrom:
          configMapKeyRef:
            name: testcm
            key: hostname
      

    This will inject the host's $HOSTNAME into the Pod's $TEST.

    If it's sensitive information, you can use Secrets instead of using ConfigMap.