Kubernetes Environment Variables in Pod or Secret or Configmap-DecodingDevOps

Kubernetes Environment Variables in Pod or Secret or Configmap-DecodingDevOps

In this article, we are going to discuss how we can use environment variables in kubernetes pod or secrets or in configmap. To create environment variable in the pod, we can specify “env:” or “envForms:” field in the definition file. By creating environment variable you will be able to use it inside the container when it starts.

Example of creating Environment Variables in Kubernetes

Let’s look at the example of how you can create environment variables in kubernetes.

 Create a file named: example.yaml

apiVersion: v1
kind: Pod
metadata:
  name: envar-demo
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: envar-demo-container
    image: gcr.io/google-samples/node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"

Execute the command shown below to create a pod from this file.

kubectl  create -f example.yaml

In this example, we have created two env. DEMO_GREETING which contains “Hello from the environment” and DEMO_FIREWELL which contains “Such a sweet sorrow”. You can list the pods using labels set on the pod. Use the command shown below to list the pod. Wait for its status to become running.

kubectl get pods -l purpose: demonstrate-envars

Go to the shell of the running container by using command,

kubectl exec -it envar-demo -- /bin/bash

To list out the environment variable enter “printenv” inside the shell you just got into.

You will find the variables we defined there.

Kubernetes Environment Variable Example 2

You can also use the env variables in the definition file itself to configure pod. Let see an example of such file.

Create a file named: var-example.yaml

apiVersion: v1
kind: Pod
metadata:
  name: print-greeting
spec:
  containers:
  - name: env-print-demo
    image: bash
    env:
    - name: GREETING
      value: "Hi"
    - name: HONORIFIC
      value: "DecodingDevOps"
    - name: NAME
      value: "Kubernetes"
    command: ["echo"]
    args: ["$(GREETING) $(HONORIFIC) $(NAME)"]

You can create this pod by executing the command below.

kubectl create -f var-example.yaml

Here, we have defined the command echo and args as the string you want to print.

We have defined the variables in the env field, which can be referenced in the args fields. 

When this pod will run successfully it will output Hi DecodingDevOps Kubernetes.

  • Kubernetes Environment Variables in Pod
  • Environment Variables in Pod Kubernetes
  • kubernetes environment variables from configmap
  • environment variables from file kubernetes
  • kubernetes environment variables from secret