Kubernetes: How to refer to one environment variable from another?

The correct syntax is to use $(FOO), as is described in the v1.EnvVar value: documentation; the syntax you have used is "shell" syntax, which isn't the way kubernetes interpolates variables. So:

containers:
- env:
  - name: POD_ID
    valueFrom: # etc etc
  - name: LOG_PATH
    value: /var/log/mycompany/$(POD_ID)/logs

Also please note that, as mentioned in the Docs, the variable to expand must be defined before the variable referencing it.


I'd just like to add to this question, a caveat we ran into the other day. According to the documentation:

Variable references $(VAR_NAME) are expanded using the previous defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged.

Emphasis mine. If you have

  - name: POD_ID
    valueFrom: # etc etc
  - name: LOG_PATH
    value: /var/log/mycompany/$(POD_ID)/logs

it will work, but if you have

  - name: LOG_PATH
    value: /var/log/mycompany/$(POD_ID)/logs
  - name: POD_ID
    valueFrom: # etc etc

it will not. If you're using a templating engine to generate your specs, beware.

Tags:

Kubernetes