how to extend environment variable for a container in Kubernetes

7/14/2017

Kubernetes documentation on setting environment variables of a container only include examples of new environment variables.

This approach does not work when I try to extend an existing environment variable PATH:

kind: Pod
apiVersion: v1
spec:
  containers:
    - name: blah
      image: blah
      env:
        - name: PATH
          value: "$PATH:/usr/local/nvidia/bin"

The created pod keeps crashing with

BackOff       Back-off restarting failed container
FailedSync    Error syncing pod

Any recommendations as to how I could extend the PATH environment variable?

-- Lana Nova
kubernetes

3 Answers

3/17/2020

If you expect the environment variable PATH to be updated with additional directory both for your container startup program and even when you want to get into the container using kubectl exec, you can update your manifest command argument something like below

spec:
  containers:
  - name: mysvc-daemon
    command:
    - /bin/bash
    - -c
    args: 
    - |
      echo 'export PATH=$PATH:$HOME/bin:$HOME/local/bin' >> $HOME/.bashrc

And then you can ensure to put the binary files in the directory $HOME/bin or $HOME/local/bin. If you get into the bash environment and check you should be able to see the directories $HOME/bin or $HOME/local/bin are now part of PATH environment variable

-- Saga
Source: StackOverflow

7/14/2017

The final environment variable is not known before the pod is started, so Kubernetes cannot append a string for which the value is unpredictable.

Indeed, docker will reset the environment variables, and eventually add its own.

What you can do is modify your entrypoint so that you can handle preparing the environment for your execution.

I have a featured bash-only entrypoint here

-- Fabien
Source: StackOverflow

7/14/2017

If you only need this path declaration for the command you are running with, you can add it to containers section, under args

Example:

spec:
  containers:
  - name: blah
    image: blah
    args:
    - PATH="$PATH:/usr/local/nvidia/bin" blah

If you do not have args specified in your yaml, you probably have a CMD specified in your Dockerfile that will just run your container with the command automatically. Thus you can add the following to your Dockerfile.

CMD ["PATH=$PATH:/usr/local/nvidia/bin", "blah"]

If you want this to be in your container in general, you would have to add to the .profile or .bashrc file of the user within the container you are using. This will probably involve creating a new image with these new files baked in.

-- Lindsay Landry
Source: StackOverflow