New batchZero to DevOps starts 29 Nov · limited seatsReserve your seat
Cheat sheetsGitHub ActionsGitHub Actions
FreeSheet 02 of 6

Environment Variables & Secrets

A comprehensive developer cheatsheet covering GitHub Actions environment variables, secrets, and contexts, featuring essential YAML configurations and operational workflows for variable precedence, default variables, and secure credential management.

Environment Variables Overview

What are Environment Variables?

Environment variables in GitHub Actions are key-value pairs that can be used across jobs, steps, and workflows. They provide configuration and context for your automation.

Types of Environment Variables

TypeScopeDescription
Workflow VariablesEntire workflowDefined at top level
Job VariablesSingle jobDefined within a job
Step VariablesSingle stepSet/used within a step
Default VariablesAll workflowsAutomatically set by GitHub
SecretsAll workflowsEncrypted sensitive data

Default Environment Variables

VariableDescriptionExample
GITHUB_ACTORUser who triggered the workflowbob
GITHUB_REPOSITORYRepository namemyuser/myapp
GITHUB_REFBranch or tag refrefs/heads/main
GITHUB_SHACommit SHAabc123def456...
GITHUB_WORKFLOWWorkflow nameCI Pipeline
GITHUB_RUN_IDUnique run ID1234567890
GITHUB_RUN_NUMBERRun number (sequential)42
GITHUB_ACTORUsername of the actorbob
GITHUB_REF_NAMEBranch or tag namemain
GITHUB_REF_TYPERef type (branch, tag)branch
GITHUB_EVENT_NAMEName of triggering eventpush
GITHUB_WORKSPACEWorkspace directory/home/runner/work/myapp
RUNNER_OSRunner OSLinux, Windows, macOS
RUNNER_TEMPTemporary directory/home/runner/work/_temp

Setting Environment Variables

1. Workflow-Level Variables

yaml
name: CI Pipeline

# Global environment variables (available to all jobs)
env:
  NODE_VERSION: '18'
  REGISTRY: 'docker.io'
  APP_NAME: 'myapp'
  REGION: 'us-east-1'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Node version: ${{ env.NODE_VERSION }}"

2. Job-Level Variables

yaml
jobs:
  build:
    runs-on: ubuntu-latest
    # Job-specific variables (override global)
    env:
      NODE_VERSION: '20'  # Overrides global
      ENVIRONMENT: 'production'
    steps:
      - run: echo "Node version: ${{ env.NODE_VERSION }}"
      - run: echo "Environment: ${{ env.ENVIRONMENT }}"

3. Step-Level Variables

yaml
steps:
  - name: Set a step variable
    run: |
      echo "MY_VAR=Hello World" >> $GITHUB_ENV
      echo "CURRENT_TIME=$(date)" >> $GITHUB_ENV

  - name: Use the step variable
    run: |
      echo "Value: ${{ env.MY_VAR }}"
      echo "Time: ${{ env.CURRENT_TIME }}"

4. Dynamic Variables from Commands

yaml
steps:
  - name: Set dynamic variable
    id: vars
    run: |
      echo "VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT
      echo "COMMIT=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

  - name: Use dynamic variable
    run: |
      echo "Version: ${{ steps.vars.outputs.VERSION }}"
      echo "Commit: ${{ steps.vars.outputs.COMMIT }}"

5. Using $GITHUB_ENV for Step Variables

yaml
steps:
  - name: Set multiple variables
    run: |
      echo "DEPLOY_ENV=staging" >> $GITHUB_ENV
      echo "BUILD_NUMBER=${{ github.run_number }}" >> $GITHUB_ENV
      echo "SHORT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_ENV

  - name: Use variables
    run: |
      echo "Deploying to ${{ env.DEPLOY_ENV }}"
      echo "Build #${{ env.BUILD_NUMBER }}"

Secrets Overview

What are Secrets?

Secrets are encrypted environment variables used to store sensitive information like API keys, passwords, and tokens. They are never exposed in logs.

Types of Secrets

TypeDescriptionUse Case
Repository SecretsAvailable in current repoAPI keys, tokens
Organization SecretsAvailable across orgShared credentials
Environment SecretsAvailable in specific environmentEnvironment-specific secrets
Dependabot SecretsFor Dependabot PRsDependabot access

Adding Secrets

Repository: Settings → Secrets and variables → Actions → New repository secret

Environment: Settings → Environments → New environment → Add secret

Organization: Organization Settings → Secrets and variables → Actions → New organization secret

Secret Naming Convention

text
- Use UPPERCASE_WITH_UNDERSCORES
- Be descriptive (e.g., AWS_ACCESS_KEY_ID, DOCKER_PASSWORD)
- Don't use spaces or special characters

Using Secrets in Workflows

1. Basic Secret Usage

yaml
steps:
  - name: Use a secret
    run: |
      echo "Deploying with API key: ${{ secrets.API_KEY }}"
    env:
      API_KEY: ${{ secrets.API_KEY }}

** WARNING:** Secrets are masked in logs, but avoid printing them!

2. Using Secrets as Environment Variables

yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production  # Env-specific secrets
    env:
      AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    steps:
      - run: aws s3 ls

3. Using Secrets with Actions

yaml
steps:
  - name: Login to Docker Hub
    uses: docker/login-action@v3
    with:
      username: ${{ secrets.DOCKER_USERNAME }}
      password: ${{ secrets.DOCKER_PASSWORD }}

  - name: Configure AWS credentials
    uses: aws-actions/configure-aws-credentials@v4
    with:
      aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
      aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
      aws-region: us-east-1

  - name: Deploy with kubectl
    run: |
      echo "${{ secrets.KUBE_CONFIG }}" > kubeconfig
      kubectl apply -f deployment.yaml --kubeconfig=kubeconfig

4. Secrets in Environment Files

yaml
steps:
  - name: Create .env file from secrets
    run: |
      echo "DATABASE_URL=${{ secrets.DATABASE_URL }}" >> .env
      echo "API_KEY=${{ secrets.API_KEY }}" >> .env
      echo "REDIS_URL=${{ secrets.REDIS_URL }}" >> .env

5. Contextual Secrets (GITHUB_TOKEN)

yaml
steps:
  - name: Create PR comment
    uses: actions/github-script@v7
    with:
      github-token: ${{ secrets.GITHUB_TOKEN }}
      script: |
        github.rest.issues.createComment({
          issue_number: context.issue.number,
          owner: context.repo.owner,
          repo: context.repo.repo,
          body: 'Build completed successfully!'
        })

Contexts

Available Contexts

ContextDescriptionExample
githubGitHub event payloadgithub.ref
envEnvironment variablesenv.NODE_VERSION
secretsSecretssecrets.API_KEY
inputsWorkflow inputsinputs.environment
runnerRunner inforunner.os
strategyMatrix strategystrategy.matrix.node-version
matrixMatrix variablesmatrix.node-version
needsJob dependenciesneeds.build.outputs.version
stepsStep outputssteps.setup.outputs.version

Common Context Usage

yaml
jobs:
  build:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.vars.outputs.VERSION }}
    steps:
      - id: vars
        run: echo "VERSION=1.0.0" >> $GITHUB_OUTPUT

  deploy:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - run: echo "Version: ${{ needs.build.outputs.version }}"
      - run: echo "Ref: ${{ github.ref }}"
      - run: echo "Runner OS: ${{ runner.os }}"
      - run: echo "Event: ${{ github.event_name }}"

GitHub Context Examples

yaml
steps:
  - name: Debug GitHub context
    run: |
      echo "Repository: ${{ github.repository }}"
      echo "Actor: ${{ github.actor }}"
      echo "Ref: ${{ github.ref }}"
      echo "SHA: ${{ github.sha }}"
      echo "Workflow: ${{ github.workflow }}"
      echo "Run ID: ${{ github.run_id }}"
      echo "Run Number: ${{ github.run_number }}"
      echo "Event Name: ${{ github.event_name }}"
      echo "Workspace: ${{ github.workspace }}"

Variable Precedence

Precedence Order (Highest to Lowest)

LevelScopeExample
1. Step envSingle stepenv: { VAR: 'step' }
2. Job envSingle jobenv: { VAR: 'job' }
3. Workflow envEntire workflowenv: { VAR: 'workflow' }
4. GITHUB_ENVStep outputecho "VAR=value" >> $GITHUB_ENV
5. Default varsGitHub defaultsGITHUB_REF, RUNNER_OS

Example: Override Precedence

yaml
name: Precedence Demo
env:
  VAR: 'workflow-level'

jobs:
  demo:
    runs-on: ubuntu-latest
    env:
      VAR: 'job-level'
    steps:
      - name: Step variable
        env:
          VAR: 'step-level'
        run: echo "Value: ${{ env.VAR }}"  # Outputs: "step-level"
      
      - name: No step variable
        run: echo "Value: ${{ env.VAR }}"  # Outputs: "job-level"
      
      - name: Set via GITHUB_ENV
        run: echo "VAR=GITHUB_ENV-level" >> $GITHUB_ENV
      
      - name: After GITHUB_ENV
        run: echo "Value: ${{ env.VAR }}"  # Outputs: "GITHUB_ENV-level"

Quick Reference — Most Used Commands

TaskYAML Snippet
Set workflow env varenv: { NODE_VERSION: '18' }
Set job env varenv: { ENV: 'production' }
Set step env varenv: { VAR: 'value' }
Set via GITHUB_ENVecho "VAR=value" >> $GITHUB_ENV
Set outputecho "value=123" >> $GITHUB_OUTPUT
Use env var${{ env.VAR }}
Use secret${{ secrets.API_KEY }}
Use context${{ github.ref }}
Use output from step${{ steps.step-id.outputs.value }}
Use output from job${{ needs.job.outputs.value }}

Pro Tips

  1. Never print secrets — they'll be masked but still exposed in logs.

  2. Use GITHUB_TOKEN — built-in secret for GitHub API access.

  3. Environment-specific secrets — use Environments for staging/prod.

  4. Secret rotation — regularly rotate secrets for security.

  5. Use env before with — for action-specific environment variables.

  6. Check variable precedence — when overriding.

  7. Use ${{ github.event.inputs }} — for manual workflow inputs.

  8. Debug with echo — but don't print secrets:

    yaml
    - run: echo "Debug: ${{ env.SAFE_VAR }}"
  9. Use if with contexts — conditional execution:

    yaml
    if: github.ref == 'refs/heads/main' && github.actor == 'bob'
  10. Secrets in PRs — secrets aren't available to PRs from forks for security.


Next in GitHub ActionsBuild & Test Workflows