Is your Pod’s environment variable not resolving a reference to another variable?

Order Matters

Paul Dally
2 min readMar 15, 2024
Photo by Growtika on Unsplash

The following would seem to be well documented in the Kubernetes documentation. However, based on the number of questions I receive on this topic, it seems to be something worth repeating:

You must define an environment variable before you can use its value in another environment variable. The definition of the “dependent” environment variable must be after the definition of the environment variable upon which it depends in your Pod spec’s containers (or initContainers).

Consider the following Pod:

apiVersion: v1
kind: Pod
metadata:
name: dependent-envars
namespace: default
spec:
containers:
- name: demo
args:
- while true; do echo -en '\n'; printf URL=$URL'\n'; sleep 30; done;
command:
- sh
- -c
image: busybox:1.36.1
env:
- name: URL
value: "$(PROTOCOL)://localhost:8080"
- name: PROTOCOL
value: "https"

The reference to $(PROTOCOL) in the URL environment variable will not be resolved, and the log will look like this:

URL=$(PROTOCOL)://localhost:8080

URL=$(PROTOCOL)://localhost:8080

...

However, try simply switching the order of the environment variable definitions so that the definition of PROTOCOL precedes that of URL:

apiVersion: v1
kind: Pod
metadata:
name: dependent-envars
namespace: default
spec:
containers:
- name: demo
args:
- while true; do echo -en '\n'; printf URL=$URL'\n'; sleep 30; done;
command:
- sh
- -c
image: busybox:1.36.1
env:
- name: PROTOCOL
value: "https"
- name: URL
value: "$(PROTOCOL)://localhost:8080"

The log will now look like this:

URL=https://localhost:8080

URL=https://localhost:8080

...

--

--

Paul Dally

AVP, IT Foundation Platforms Architecture at Sun Life Financial. Views & opinions expressed are my own, not necessarily those of Sun Life