Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes: How to expand env variables from configmap

I'm using config maps to inject env variables into my containers. Some of the variables are created by concatenating variables, for example:

~/.env file

HELLO=hello
WORLD=world
HELLO_WORLD=${HELLO}_${WORLD}

I then create the config map

kubectl create configmap env-variables --from-env-file ~/.env

The deployment manifests reference the config map.

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    spec:
      containers:
      - name: my-image
        image: us.gcr.io/my-image
        envFrom:
        - configMapRef:
            name: env-variables

When I exec into my running pods, and execute the command

$ printenv HELLO_WORLD

I expect to see hello_world, but instead I see ${HELLO}_${WORLD}. The variables aren't expanded, and therefore my applications that refer to these variables will get the unexpanded value.

How do I ensure the variables get expanded?

If it matters, my images are using alpine.

like image 966
Eric Guan Avatar asked Aug 25 '18 00:08

Eric Guan


People also ask

How do I get environment variables in Kubernetes?

We have to use the 'printenv' to list the pod's container environment variables. It lists all environment variables including variables specified explicitly in the YAML file. We can also reference environment variables from configMap as well.

How do I pass an env file in Kubernetes?

There are two ways to define environment variables with Kubernetes: by setting them directly in a configuration file, from an external configuration file, using variables, or a secrets file. This tutorial shows both options, and uses the Humanitec getting started application used in previous tutorials.


1 Answers

I can't find any documentation on interpolating environment variables, but I was able to get this to work by removing the interpolated variable from the configmap and listing it directly in the deployment. It also works if all variables are listed directly in the deployment. It looks like kubernetes doesn't apply interpolation to variables loaded from configmaps.

For instance, this will work:

Configmap

apiVersion: v1
data:
  HELLO: hello
  WORLD: world
kind: ConfigMap
metadata:
  name: env-variables
  namespace: default

Deployment:

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-app
spec:
  template:
    spec:
      containers:
      - name: my-image
        image: us.gcr.io/my-image
        envFrom:
        - configMapRef:
            name: env-variables
        env:
        - name: HELLO_WORLD
          value: $(HELLO)_$(WORLD)
like image 188
Grant David Bachman Avatar answered Sep 30 '22 03:09

Grant David Bachman