Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kubernetes

I've a Deployment object where I expose the POD ID using the Downward API. That works fine. However, I want to set up another env variable, log path, with reference to the POD ID. But, setting that variable value to /var/log/mycompany/${POD_ID}/logs isn't working, no logs are created in the container. I can make the entrypoint script or the app aware of the POD ID, and build up the log path, but I'd rather not do that.

like image 725
Abhijit Sarkar Avatar asked Mar 30 '18 22:03

Abhijit Sarkar


People also ask

How do you pass arguments in Kubernetes?

Define Commands and Arguments for a Kubernetes Pod We can pass these arguments to the command using the args field. In the below example, we have passed the command printenv to the container for it to print the values for the environment variable KUBECONFIG as an argument to it.


2 Answers

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.

like image 134
mdaniel Avatar answered Oct 23 '22 03:10

mdaniel


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.

like image 29
Jonathan Lynch Avatar answered Oct 23 '22 02:10

Jonathan Lynch