Skip to content

Latest commit

 

History

History
104 lines (77 loc) · 2.47 KB

File metadata and controls

104 lines (77 loc) · 2.47 KB

GitHub Actions: Environment Variables & Secrets


Environment variables and secrets allow you to pass configuration and sensitive data into your workflows without hardcoding values. This keeps workflows flexible and credentials secure.


1. Environment Variables (env)

  • Used to pass non-sensitive configuration into steps.
  • Can be defined at three levels: workflow, job, or step.

Workflow-level (available to all jobs and steps)

env:
  NODE_ENV: production
  APP_NAME: my-app

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Print env
        run: echo "App: $APP_NAME, Env: $NODE_ENV"

Job-level (available to all steps in that job)

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      BUILD_MODE: release
    steps:
      - run: echo "Mode: $BUILD_MODE"

Step-level (available only to that step)

steps:
  - name: Run with custom var
    env:
      GREETING: Hello
    run: echo "$GREETING from GitHub Actions"

2. Secrets

  • Used for sensitive values like API keys, tokens, and passwords.
  • Stored securely in GitHub repository settings (Settings → Secrets and variables → Actions).
  • Never printed in logs — GitHub automatically masks them.
  • Accessed using ${{ secrets.SECRET_NAME }}.

Adding a secret

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

Using secrets in a workflow

steps:
  - name: Deploy
    env:
      API_KEY: ${{ secrets.API_KEY }}
      DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
    run: ./deploy.sh

3. GitHub's Built-in Environment Variables

GitHub automatically provides several variables in every workflow:

Variable Description
GITHUB_REPOSITORY Owner and repo name (user/repo)
GITHUB_REF Full ref of the branch or tag
GITHUB_SHA Commit SHA that triggered the workflow
GITHUB_ACTOR Username that triggered the workflow
GITHUB_WORKSPACE Path to the checked-out repository
- name: Print built-ins
  run: |
    echo "Repo: $GITHUB_REPOSITORY"
    echo "SHA: $GITHUB_SHA"
    echo "Actor: $GITHUB_ACTOR"

Key Rules

  • Never hardcode secrets — always use ${{ secrets.NAME }}.
  • Secrets are not available in fork pull requests by default (security measure).
  • Environment variables are case-sensitive on Linux runners.
  • Use env: at the step level when a variable is only needed for one step.