How to set environment variable in container from Kubernetes?

2/28/2019

I want to set an environment variable (I'll just name it ENV_VAR_VALUE) to a container during deployment through Kubernetes.

I have the following in the pod yaml configuration:

...
...
    spec:
      containers:
      - name: appname-service
        image: path/to/registry/image-name
        ports:
        - containerPort: 1234
        env:
        - name: "ENV_VAR_VALUE"
          value: "some.important.value"
...
...

The container needs to use the ENV_VAR_VALUE's value.
But in the container's application logs, it's value always comes out empty.
So, I tried checking it's value from inside the container:

$ kubectl exec -it appname-service bash
root@appname-service:/# echo $ENV_VAR_VALUE
some.important.value
root@appname-service:/# 

So, the value was successfully set.

I imagine it's because the environment variables defined from Kubernetes are set after the container is already initialized.

So, I tried overriding the container's CMD from the pod yaml configuration:

...
...
    spec:
      containers:
      - name: appname-service
        image: path/to/registry/image-name
        ports:
        - containerPort: 1234
        env:
        - name: "ENV_VAR_VALUE"
          value: "some.important.value"
        command: ["/bin/bash"]
        args: ["-c", "application-command"]
...
...

Even still, the value of ENV_VAR_VALUE is still empty during the execution of the command.
Thankfully, the application has a restart function
-- because when I restart the app, ENV_VAR_VALUE get used successfully.
-- I can at least do some other tests in the mean time.

So, the question is...

How should I configure this in Kubernetes so it isn't a tad too late in setting the environment variables?

As requested, here is the Dockerfile.
I apologize for the abstraction...

FROM ubuntu:18.04

RUN apt-get update && apt-get install -y some-dependencies

COPY application-script.sh application-script.sh

RUN ./application-script.sh

# ENV_VAR_VALUE is set in this file which is populated when application-command is executed
COPY app-config.conf /etc/app/app-config.conf

CMD ["/bin/bash", "-c", "application-command"]
-- libzz
kubernetes
kubernetes-pod

2 Answers

2/28/2019

Why don't you move the

RUN ./application-script.sh

below

COPY app-config.conf /etc/app/app-config.conf

Looks like the app is running before the env conf is available for it.

-- manojlds
Source: StackOverflow

2/28/2019

You can try also running two commands in Kubernetes POD spec:

  1. (read in env vars): "source /env/required_envs.env" (would come via secret mount in volume)
  2. (main command): "application-command"

Like this:


containers:
  - name: appname-service
    image: path/to/registry/image-name
    ports:
        - containerPort: 1234
    command: ["/bin/sh", "-c"]
    args:
      - source /env/db_cred.env;
        application-command;
-- Nepomucen
Source: StackOverflow