Passing host/local env vars into Kubectl 'exec' commands

2/21/2019

I'd like to pass env vars into the exec command.

So far I have tried the following

SOME_VAR="A String"

kubectl exec -it a-pod-name -- sh -c 'env NEW_VAR=$SOME_VAR; echo $NEW_VAR > some-file-name.txt'

I realise I could use kubectl cp if I wanted to copy files, but that doesn't fit my use case.

-- denski
kubectl
kubernetes

1 Answer

2/21/2019

You need to put the command in double quotes and it will work like following:

kubectl exec -it a-pod-name -- sh -c "env new_var=$var; echo $new_var > some-file-name.txt"

The reason behind that is bash doesn't extract variable into values in single quotes and hence you need to use double quotes.

-- Prafull Ladha
Source: StackOverflow