Kubernetes init container issue with environment variables

10/14/2020

I am trying to add a init container to a deployment, but I can´t make the env vars work for some reason.

Just to illustrate, this is what I am trying:

initContainers:
    - name: init-db
      image: mysql:5.7
      env:
        - name: TEST
          value: nada
      args: ["echo", "${TEST}"]

But no matter what I do, the env vars doesn´t work, the echo always returns ${TEST} instead of nada

Any hint?

-- Stargazer
kubernetes
kubernetes-helm

3 Answers

7/20/2021

According to Kubernetes official documentation, you need to use parentheses $(TEST) for the variable to be expanded in the command or args field. I had an error using brackets because the env vars were not properly expanded on args. Working example:

initContainers:
  - name: my-container
    image: 'my-image'
    envFrom:
      - configMapRef:
          name: my-config
    args:
      - '-path=/$(MY_ENV_VAR)'

Kubernetes Documentation

-- Juan García
Source: StackOverflow

10/14/2020

Like the comments and other answer mentioned you need to use shell for ENV substitution properly. therefore, replace the line

args: ["echo", "${TEST}"] in you code to

command: ['sh', '-c', 'echo ${TEST}']

Reference

-- garlicFrancium
Source: StackOverflow

10/14/2020

You need to use a shell in order to do ENV var substitution properly. For example:

initContainers:
    - name: init-db
      image: mysql:5.7
      env:
        - name: TEST
          value: nada
      command:
      - /bin/sh
      - -c
      - echo "${TEST}"
-- Eduardo Baitello
Source: StackOverflow