Understanding how to use and manage environment variables in your workflows

What are Environment Variables?

Think of environment variables as sticky notes that you can attach to your workflow. They store information that your jobs and steps can read and use.

Simple analogy: Like having a shared notebook where you write down important information (API keys, URLs, settings) that everyone in your team can reference when needed.

env:
  APP_NAME: "My Awesome App"    # Like writing "App Name: My Awesome App" on a sticky note
  NODE_VERSION: "18"            # Like writing "Use Node.js version 18" 

jobs:
  build:
    steps:
      - name: Show app info
        run: echo "Building $APP_NAME with Node.js $NODE_VERSION"
        # Outputs: "Building My Awesome App with Node.js 18"

🎯 Why Use Environment Variables?

1. Avoid Repetition

Instead of typing the same values everywhere:

# ❌ Without env vars (repetitive)
jobs:
  build:
    steps:
      - run: echo "App: My Awesome App, Version: 1.0.0"
  test:
    steps:
      - run: echo "Testing My Awesome App version 1.0.0"
  deploy:
    steps:
      - run: echo "Deploying My Awesome App v1.0.0"
# ✅ With env vars (clean and maintainable)
env:
  APP_NAME: "My Awesome App"
  VERSION: "1.0.0"

jobs:
  build:
    steps:
      - run: echo "App: $APP_NAME, Version: $VERSION"
  test:
    steps:
      - run: echo "Testing $APP_NAME version $VERSION"
  deploy:
    steps:
      - run: echo "Deploying $APP_NAME v$VERSION"

2. Store Configuration

Keep settings in one place that's easy to change:

env:
  DATABASE_URL: "postgres://localhost:5432/myapp"
  API_ENDPOINT: "<https://api.myapp.com>"
  TIMEOUT: "30"

3. Handle Sensitive Data Safely

Use with GitHub Secrets for secure information:

env:
  API_KEY: ${{ secrets.MY_API_KEY }}      # Secure way to use secrets
  DATABASE_PASSWORD: ${{ secrets.DB_PASS }}

📊 Environment Variable Scopes

Environment variables can be set at different levels, like Russian nesting dolls:

1. Workflow Level (Available to all jobs)

name: My Workflow

env:                          # 🌍 Global - available everywhere
  GLOBAL_VAR: "I'm everywhere!"
  APP_NAME: "My App"

jobs:
  job1:
    steps:
      - run: echo $GLOBAL_VAR  # ✅ Can access this
  job2:
    steps:
      - run: echo $APP_NAME    # ✅ Can access this too