DEV Community

Janak Shrestha
Janak Shrestha

Posted on

Day 57: Print Environment Variables

The Nautilus DevOps team is working on to setup some pre-requisites for an application that will send the greetings to different users. There is a sample deployment, that needs to be tested. Below is a scenario which needs to be configured on Kubernetes cluster. Please find below more details about it.

  1. Create a pod named print-envars-greeting.
  2. Configure spec as, the container name should be print-env-container and use bash image.
  3. Create three environment variables:
    a. GREETING and its value should be Welcome to
    b. COMPANY and its value should be Nautilus
    c. GROUP and its value should be Group

  4. Use command ["/bin/sh", "-c", 'echo "$(GREETING) $(COMPANY) $(GROUP)"'] (please use this exact command), also set its restartPolicy policy to Never to avoid crash loop back.

  5. You can check the output using kubectl logs -f print-envars-greeting command.

Note: The kubectl utility on the jump-host has been configured to work with the Kubernetes cluster.


What We Will Build

We are going to create a Kubernetes Pod that:

  • Runs a container using the bash image
  • Defines three environment variables
  • Executes a command that prints these variables
  • Exits after completing its task

Technical Details

Component Specification
Pod Name print-envars-greeting
Container Name print-env-container
Image bash
Restart Policy Never
Environment Variables GREETING, COMPANY, GROUP

Understanding Environment Variables in Kubernetes

Environment variables are key-value pairs that provide configuration data to containers. They are commonly used for:

  • Application configuration
  • Database connection strings
  • API endpoints
  • Feature flags
  • Credentials (though Secrets are recommended for sensitive data)

In Kubernetes, environment variables can be defined directly in the Pod specification using the env field.


Step-by-Step Implementation

Step 1: Create the Pod YAML File

Create a file named print-envars-greeting.yaml with the following content:

apiVersion: v1
kind: Pod
metadata:
  name: print-envars-greeting
spec:
  restartPolicy: Never
  containers:
  - name: print-env-container
    image: bash
    command:
    - "/bin/sh"
    - "-c"
    - 'echo "$(GREETING) $(COMPANY) $(GROUP)"'
    env:
    - name: GREETING
      value: "Welcome to"
    - name: COMPANY
      value: "Nautilus"
    - name: GROUP
      value: "Group"
Enter fullscreen mode Exit fullscreen mode

YAML Breakdown

Pod Metadata

metadata:
  name: print-envars-greeting
Enter fullscreen mode Exit fullscreen mode

This defines the name of the Pod.

Restart Policy

spec:
  restartPolicy: Never
Enter fullscreen mode Exit fullscreen mode

Never ensures the Pod runs once and does not restart. Since this is a one-time task, this policy is appropriate.

Container Definition

containers:
- name: print-env-container
  image: bash
Enter fullscreen mode Exit fullscreen mode

The container is named print-env-container and uses the bash image, which provides a lightweight shell environment.

Command Definition

command:
- "/bin/sh"
- "-c"
- 'echo "$(GREETING) $(COMPANY) $(GROUP)"'
Enter fullscreen mode Exit fullscreen mode

The command executes a shell script that echoes the values of the three environment variables.

Environment Variables

env:
- name: GREETING
  value: "Welcome to"
- name: COMPANY
  value: "Nautilus"
- name: GROUP
  value: "Group"
Enter fullscreen mode Exit fullscreen mode

Three environment variables are defined with their respective values.

Step 2: Create the Pod

Apply the YAML configuration to create the Pod:

kubectl apply -f print-envars-greeting.yaml
Enter fullscreen mode Exit fullscreen mode

Output:

pod/print-envars-greeting created
Enter fullscreen mode Exit fullscreen mode

Step 3: Verify Pod Status

Check the status of the Pod:

kubectl get pods
Enter fullscreen mode Exit fullscreen mode

Output:

NAME                    READY   STATUS      RESTARTS   AGE
print-envars-greeting   0/1     Completed   0          11s
Enter fullscreen mode Exit fullscreen mode

The Completed status indicates that the container ran successfully and exited. Since the restart policy is Never, the Pod remains in this completed state.

Step 4: View the Output

View the logs to see the output of the command:

kubectl logs print-envars-greeting
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome to Nautilus Group
Enter fullscreen mode Exit fullscreen mode

How the Command Works

The command executes as follows:

  1. The container starts with the bash image
  2. The shell interprets the command
  3. The shell substitutes each $(VARIABLE_NAME) with its value:
    • $(GREETING)Welcome to
    • $(COMPANY)Nautilus
    • $(GROUP)Group
  4. The echo command prints the concatenated string
  5. The container exits successfully

The command syntax is important. The single quotes preserve the $ characters, allowing the shell to interpret them as variable references rather than treating them as literal strings.


Environment Variable Best Practices

When to Use Environment Variables

Environment variables are ideal for:

  • Non-sensitive configuration
  • Application settings that differ between environments
  • Feature toggles
  • Service discovery information

When Not to Use Environment Variables

Consider alternatives for:

  • Sensitive data (use Secrets instead)
  • Large configuration files (use ConfigMaps)
  • Complex nested configurations (use ConfigMaps or external configuration management)

Best Practices

  1. Use descriptive names: Make variable names meaningful and consistent
  2. Document your variables: Maintain a reference of what each variable does
  3. Use Secrets for sensitive data: Never store passwords or tokens in plain text
  4. Keep it organized: Group related variables together
  5. Validate variables: Ensure required variables are set before the application starts

Common Use Cases

Application Configuration

Environment variables are commonly used to configure applications:

env:
- name: DATABASE_URL
  value: "postgres://user:pass@host:5432/db"
- name: LOG_LEVEL
  value: "debug"
- name: API_KEY
  value: "abcdef123456"
Enter fullscreen mode Exit fullscreen mode

Feature Flags

Control application features:

env:
- name: FEATURE_NEW_UI
  value: "true"
- name: FEATURE_BETA
  value: "false"
Enter fullscreen mode Exit fullscreen mode

Environment Identification

Identify the deployment environment:

env:
- name: ENVIRONMENT
  value: "production"
- name: REGION
  value: "us-east-1"
Enter fullscreen mode Exit fullscreen mode

Troubleshooting

Pod Does Not Start

# Check the Pod status
kubectl get pods

# Get detailed information
kubectl describe pod print-envars-greeting

# Check logs for errors
kubectl logs print-envars-greeting
Enter fullscreen mode Exit fullscreen mode

Variables Not Substituted

Ensure you are using the correct syntax:

  • Use $(VAR_NAME) for variable substitution
  • Use single quotes to preserve $ characters
  • Verify that the variable names match exactly

Pod Is in CrashLoopBackOff

# Check the pod status
kubectl get pods

# Check logs
kubectl logs print-envars-greeting --previous

# Verify the command syntax
kubectl describe pod print-envars-greeting
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

What We Learned

  1. Environment variables in Kubernetes: Defined in the env field of a container specification
  2. Variable substitution: Use $(VAR_NAME) to reference environment variables in commands
  3. Restart policies: Never is suitable for one-time tasks
  4. Pod lifecycle: A Pod can have a Completed status after successful execution
  5. Command execution: The bash image provides a lightweight shell environment

Top comments (0)