Expose Pod Information to Containers Through Environment Variables
This page shows how a Pod can use environment variables to expose information
about itself to Containers running in the Pod. Environment variables can expose
Pod fields and Container fields.
You need to have a Kubernetes cluster, and the kubectl command-line tool must
be configured to communicate with your cluster. If you do not already have a
cluster, you can create one by using
Minikube
,
or you can use one of these Kubernetes playgrounds:
In the configuration file, you can see five environment variables. The
env
field is an array of
EnvVars
.
The first element in the array specifies that the
MY_NODE_NAME
environment
variable gets its value from the Pod’s
spec.nodeName
field. Similarly, the
other environment variables get their names from Pod fields.
Note:
The fields in this example are Pod fields. They are not fields of the
Container in the Pod.
To see why these values are in the log, look at the
command
and
args
fields
in the configuration file. When the Container starts, it writes the values of
five environment variables to stdout. It repeats this every ten seconds.
Next, get a shell into the Container that is running in your Pod:
kubectl exec -it dapi-envars-fieldref -- sh
In your shell, view the environment variables:
/# printenv
The output shows that certain environment variables have been assigned the
values of Pod fields:
Use Container fields as values for environment variables
In the preceding exercise, you used Pod fields as the values for environment
variables. In this next exercise, you use Container fields as the values for
environment variables. Here is the configuration file for a Pod that has one
container:
In the configuration file, you can see four environment variables. The
env
field is an array of
EnvVars
.
The first element in the array specifies that the
MY_CPU_REQUEST
environment
variable gets its value from the
requests.cpu
field of a Container named
test-container
. Similarly, the other environment variables get their values
from Container fields.