Kubectl set environment variables and run command

7/2/2018

I have a container running on Kubernetes where I would like to run a command from my local terminal. The working directory of the container based on its yaml file is at say /opt/gopath/src/a/. However, I would like to run the command at directory /opt/gopath/src/b/. Additionally, I also need to set certain temporary environment variables before running this command. So currently, this is what I am doing:

kubectl exec $pod_name -- bash -c "cd ../b/; env ENV_VARIABLE_1=ENV_VALUE_2 && env ENV_VARIABLE_2=ENV_VALUE_2 && <cmd to run>".

This seems to be working currently. However, I am not convinced that this is the best way to achieve this. Also, running this command displays all the environment variables in the container -- which I would like not to be printed if possible. Could anyone point me in the right direction?

-- ab15
kubectl
kubernetes

4 Answers

7/2/2018

In case of static variables, I would suggest using Config maps.

Since you need to use temporary variables from a local shell, there is no need to use long and complicated commands as exec connects your terminal to the running Container (pod). I tested your issue and created a simple environment variable on the local system. I used syntax provided by you:

kubectl exec -it $pod_name -- sh -c 'key=123 key2=121; echo "$key $key2"'

To pass env vars, you can just set it like that and add delimiter ';' between variables and your command.

-- aurelius
Source: StackOverflow

8/17/2019

This is very late but I'm sure it will be very helpful.

envsubst solves this issue in a one-liner.

The below command replaces env variables in YAML file with actual values.

cat <filename>.yaml | envsubst | kubectl apply -f -
-- Rewanth Cool
Source: StackOverflow

7/2/2018

bash -c "cd ../b/; env ENV_VARIABLE_1=ENV_VALUE_2 ENV_VARIABLE_2=ENV_VALUE_2 <cmd to run>"

-- user571470
Source: StackOverflow

9/10/2018

i would suggest specifying the details (including env variables) in a manifest .yaml file and then doing kubectl create -f manifest.yaml

This is much more reproducible than having a ton of flags in the command line.

-- cryanbhu
Source: StackOverflow