Printing Environment Variables in Kubernetes Pods

Printing Environment Variables in Kubernetes Pods

Environment variables are a powerful tool in Kubernetes for managing configuration data within your pods. They allow you to inject values directly into your containerized applications, making them dynamic and adaptable. We will look at how to deploy a pod with environment variables and then access them within the container.

Creating a Pod with Environment Variables:

kubectl run print-envars-greeting --image=bash --dry-run=client -o yaml        

The command demonstrates creating a pod named print-envars-greeting using the `kubectl run` command. The --image=bash flag specifies the container image to use (in this case, the basic bash image). The --dry-run=client -o yaml option generates the pod manifest without actually creating the pod. This allows us to inspect the generated YAML file before applying it.

Manifest with Environment Variables:

Here's the full pod manifest file with environment variables defined:

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: print-envars-greeting
  name: print-envars-greeting
spec:
  containers:
  - image: bash
    name: print-env-container
    env:
    - name: GREETING
      value: "Welcome to"
    - name: COMPANY
      value: "DevOps"
    - name: GROUP
      value: "Datacenter"
    command:
    - /bin/sh
    - -c
    - echo $GREETING $COMPANY $GROUP
  dnsPolicy: ClusterFirst
  restartPolicy: Never        

This manifest defines a pod named print-envars-greeting with a single container named print-env-container. The env section within the container definition specifies three environment variables:

  • GREETING: Set to "Welcome to"
  • COMPANY: Set to "DevOps"
  • GROUP: Set to "Datacenter"

The command section instructs the container to run the /bin/sh shell and execute the echo command, printing the values of the defined environment variables.

Accessing Environment Variables:

Once the pod is created with our defined environment variables, we can access them within the container using the printenv or env commands.

kubectl exec -it print-envars-greeting bash

# inside container run 
printenv        

You can also achieve this with kubectl set env. The kubectl set env command allows managing environment variables directly on pods that are already running.

Define Environment Variables for a Container


To view or add a comment, sign in

More articles by Omar Mohamed

Insights from the community

Others also viewed

Explore topics