Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes kubectl access environment variables

Does anyone know why this one doesn't (shows empty line):

kubectl exec kube -- echo $KUBERNETES_SERVICE_HOST

but this one works?

kubectl exec kube -- sh -c 'echo $KUBERNETES_SERVICE_HOST'
like image 400
Kim Avatar asked May 12 '19 20:05

Kim


People also ask

How do I view Kubernetes environment variables?

We have to use the 'printenv' to list the pod's container environment variables. It lists all environment variables including variables specified explicitly in the YAML file. We can also reference environment variables from configMap as well.

How do you pass environment variables in pod?

When you create a Pod, you can set dependent environment variables for the containers that run in the Pod. To set dependent environment variables, you can use $(VAR_NAME) in the value of env in the configuration file.

How do I pass an env file in Kubernetes?

There are two ways to define environment variables with Kubernetes: by setting them directly in a configuration file, from an external configuration file, using variables, or a secrets file. This tutorial shows both options, and uses the Humanitec getting started application used in previous tutorials.


2 Answers

Running successfully will depend on the image that you are using for kube. But in general terms echo is a built-in Bourne shell command.

With this command:

$ kubectl exec kube -- echo $KUBERNETES_SERVICE_HOST

You are not instantiating a Bourne Shell environment and there is not an echo executable in the container. It turns out what kubectl does is basically running echo $KUBERNETES_SERVICE_HOST on your client! You can try running for example:

$ kubectl exec kube -- echo $PWD

You'll see that is the home directory on your client.

Whereas with this command:

$ kubectl exec kube -- sh -c 'echo $KUBERNETES_SERVICE_HOST'

There is a sh executable in your environment and that's Bourne Shell that understands the built-in echo command with the given Kubernetes environment in the default container of your Pod.

like image 191
Rico Avatar answered Oct 18 '22 22:10

Rico


One option that usually works without sh -c, in case it's needed, is:

kubectl exec kube -- env | grep KUBERNETES_SERVICE_HOST
like image 40
yuranos Avatar answered Oct 19 '22 00:10

yuranos