Kubernetes: How to push ConfigMap values as environment variables

2 min read | by Jordi Prats

We can read values from a ConfigMap as a volume but we can present them to a Pod as an environment variable

Let's assume we have the following ConfigMap that we want to use to populate environment variables to a Deployment:

apiVersion: v1 kind: ConfigMap metadata:  name: envvars-cm data:  VALUE_FROM_CONFIGMAP: '99' 

We can read the values from the ConfigMap and push them as environment variables to a container using envFrom and configMapRef as follows:

apiVersion: apps/v1 kind: Deployment metadata:  name: demo spec:  replicas: 1  selector:  matchLabels:  app: demo  template:  metadata:  labels:  app: demo  spec:  containers:  - name: ampa  image: alpine:latest  args: [ "sleep", "3600" ]  env:  - name: DIRECT_VALUE  value: '00'  envFrom:  - configMapRef:  name: envvars-cm 

We can see how the data we have on the ConfigMap can be retrieved from the container that has the envFrom.configMapRef as an environment variable:

$ kubectl exec -i deploy/demo -- env | grep VALUE VALUE_FROM_CONFIGMAP=99 DIRECT_VALUE=00 

Posted on 27/10/2022