Run Tests Up to 70% Faster than Traditional Test Grids

HyperExecute Is an AI-Native Test Orchestration Platform to Run Your Automation Test Suites with Blazing Fast Speed.

GitHub Actions Environment Variables: How to Set, Share and Scope Them

How GitHub Actions environment variables work: env at workflow, job and step level, vars per environment, GITHUB_ENV, GITHUB_OUTPUT and default variables.

Published

Summarise with AI

GitHub Actions environment variables are key-value pairs that your workflow passes to the steps. You can set them at the workflow, job or step level using the env key.

You can also store reusable settings as configuration variables which you can then reference throughout your workflow using ${{ vars.NAME }}. You can pass a value to a later step by simply writing NAME=value to $GITHUB_ENV. The most specific env definition wins.

TL;DR

GitHub Actions environment variables come from three places: the env key in a workflow file, configuration variables read with ${{ vars.NAME }}, and values a step writes to $GITHUB_ENV for later steps. The most specific env definition wins, and an unset configuration variable resolves to an empty string, so guard every value a test needs.

Where Each GitHub Actions Value Lives

  • Set an environment variable: In GitHub Actions, set an environment variable with an env map at workflow, job or step level; a step value overrides the job value, which overrides the workflow value.
  • GitHub Actions env vs vars: GitHub Actions env values live in the workflow file, while GitHub Actions vars live in organization, repository or environment settings and change without a commit.
  • GitHub repository variables: Create GitHub repository variables under Settings > Secrets and variables > Actions > Variables; every workflow in the repository can read them. Masked in logs: No.
  • GitHub Actions configuration variables: For GitHub Actions configuration variables, an environment-level value beats a repository value, which beats an organization value, and reusable workflows read the caller repository's values.
  • GITHUB_ENV: Appending NAME=value to $GITHUB_ENV passes a value to later steps in the same job. Readable by the step that writes it: No.
  • HyperExecute: TestMu AI's HyperExecute takes GitHub Actions environment variables through --vars and maps them into env in hyperexecute.yaml; with strict: true, a missing variable stops the CLI before upload.

What Are Environment Variables in GitHub Actions?

GitHub Actions reads variables from three sources:

  • Custom environment variables that you declare with env: in a workflow file. They only exist in that workflow.
  • Configuration variables that you create in your repository, environment or organization settings. GitHub's documentation refers to these as variables, and workflows will access them via the vars context. Many workflows can make use of them.
  • Default environment variables that GitHub sets on every runner (e.g. CI, GITHUB_SHA, RUNNER_OS).

Keep base URLs, browser names and feature switches in variables rather than in test code. Then one suite runs unchanged on a laptop, in a pull request check and against staging. Separating code from configuration is a basic habit in automation testing, and GitHub Actions gives you these three places to put the configuration.

For a quick visual walkthrough of this concept, watch the video below from TestMu AI.

Youtube thumbnail

Subscribe to the TestMu AI YouTube channel for more tutorials on testing and automation.

How Do You Set an Environment Variable at Workflow, Job and Step Level?

GitHub Actions uses the env key to set custom variables, and the scope of each variable is the block that it's in. The workflow syntax reference states: "When more than one environment variable is defined with the same name, GitHub uses the most specific variable."

name: e2e
on: [pull_request]
env:                     # workflow level: every job
  TEST_BROWSER: chromium
jobs:
  e2e:
    runs-on: ubuntu-latest
    env:                 # job level: every step in this job
      TEST_BROWSER: firefox
    steps:
      - run: echo "$TEST_BROWSER"      # prints firefox
      - run: echo "$TEST_BROWSER"      # prints webkit
        env:             # step level: this step only
          TEST_BROWSER: webkit
GitHub Actions env precedence: step-level env overrides job-level, which overrides workflow-level.

Two rules from the same reference catch people out:

  • Variables in one env map "cannot be defined in terms of other variables in the map". So URL: ${{ env.HOST }}/login won't work within the same block.
  • A step-level variable is only visible within that step. It doesn't carry over to the next step.

What's the Difference Between env and vars in GitHub Actions?

env is defined in the workflow file, and vars are defined in GitHub settings.

  • Use env for values that are part of one workflow and which will be changed by the code (e.g. a Node version or a reporter name).
  • Use vars for values that vary by deployment target or are used across multiple workflows (e.g. a staging URL, a test tenant ID, etc.). Someone can change them without a commit.

GitHub's guide to using variables gives the settings paths:

  • Repository or organization: Settings > Secrets and variables > Actions > Variables.
  • Environment: Settings > Environments > [environment] > Environment variables.

A workflow reads them like this:

steps:
  - run: echo "Testing $BASE_URL"
    env:
      BASE_URL: ${{ vars.BASE_URL }}

GitHub's guide states that an unset variable's expression "will be an empty string". The workflow continues to run, so a missing value manifests itself later as a rather confusing test failure. Add a guard (see the SCOPE check below).

When the same config variable name exists at multiple levels, the variable reference says the lowest level wins (environment > repository > organization).

GitHub's variables overview makes it very clear that variables "render unmasked in your build outputs".

Never store a password or token in vars.

Note

Note: Can you run a suite on remote machines? HyperExecute from TestMu AI will run your existing tests from a GitHub Actions step and takes the same variables in via your YAML. The free plan is 300 free minutes on up to 2 concurrent Windows or Linux VMs. Go for free and point one of your workflows at it.

How Do You Use Different Variables for Staging and Production?

GitHub environments let one workflow read different values for each target:

  • Create two environments: staging and production.
  • Add a BASE_URL variable to each.
  • Reference the environment on the job:
jobs:
  e2e:
    runs-on: ubuntu-latest
    environment: ${{ github.event_name == 'push' && 'production' || 'staging' }}
    env:
      BASE_URL: ${{ vars.BASE_URL }}
    steps:
      - run: echo "Running against $BASE_URL"

The environment-level BASE_URL takes precedence over the repository-level one. You can therefore have a repository-level default and then override that per environment.

The variables reference also includes a caveat: "Environment-level variables are only available on the runner after the job starts executing." A job-level if: is evaluated before that, so check them in a step rather than in a job-level condition.

Sensitive values per environment (e.g. a staging test user's password) should be in environment secrets rather than variables. Our guide to GitHub Actions secrets covers scopes, masking and what happens on PRs from forks.

How Do You Pass a Value From One Step to Another via GITHUB_ENV?

Each step runs in its own shell, so if you export NAME=value in one step, that's not going to be available in the next. GitHub Actions deals with this via an environment file. You append NAME=value to the file at $GITHUB_ENV and all the subsequent steps in the job will see that.

The workflow commands are very explicit about this: only the steps that come after can see the value; the step that wrote it can't.

- name: Build a run label
  run: echo "RUN_LABEL=${GITHUB_REF_NAME}-${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_ENV"
- name: Use it
  run: echo "Uploading report as $RUN_LABEL"

For multiline values, GitHub documents a delimiter form:

{
  echo "CHANGED_SPECS<<EOF"
  git diff --name-only origin/main -- tests/
  echo "EOF"
} >> "$GITHUB_ENV"

Pick a delimiter that can't appear on a line of its own inside the value. Two more limits apply:

  • GITHUB_* and RUNNER_* variables cannot be overwritten.
  • GITHUB_ENV can't set NODE_OPTIONS.

To load a committed settings file for every later step, append its lines to the same file:

- name: Load shared test settings
  run: grep -v '^#' ci/test.env | grep '=' >> "$GITHUB_ENV"

Just keep it as plain NAME=value lines and absolutely don't put a credential in there.

When to Use GITHUB_OUTPUT Rather Than GITHUB_ENV?

Use GITHUB_ENV to pass a value to later steps in the same job. Use GITHUB_OUTPUT when you want another job or a named later step to have access to the value. Outputs require a step id, and they can be shared across jobs via needs:

jobs:
  plan:
    runs-on: ubuntu-latest
    outputs:
      target: ${{ steps.pick.outputs.target }}
    steps:
      - id: pick
        run: echo "target=staging" >> "$GITHUB_OUTPUT"
  test:
    needs: plan
    runs-on: ubuntu-latest
    steps:
      - run: echo "Testing ${{ needs.plan.outputs.target }}"

GitHub caps output at 1MB per job and 50MB per workflow run. Building a full test matrix from a job output is covered in the GitHub Actions matrix guide.

How Do env, vars, secrets, GITHUB_ENV and GITHUB_OUTPUT Compare?

OptionWhere it is setHow you read itScopeMasked in logsTypical values
env:Workflow file (workflow, job, step)$NAME in shell, ${{ env.NAME }} in expressionsBlock it is defined in; most specific winsNoReporter name, Node version, default browser
vars (configuration variables)Settings: organization, repository, environment${{ vars.NAME }}Every workflow that can see that level; environment > repository > organizationNoStaging URL, test tenant ID
secretsSettings: organization, repository, environment${{ secrets.NAME }}Same levels as varsYesTest user password, LT_ACCESS_KEY
$GITHUB_ENVWritten by a step at runtime$NAME in later stepsLater steps of the same jobNoRun label, computed build version
$GITHUB_OUTPUTWritten by a step with an idsteps.<id>.outputs.NAME, needs.<job>.outputs.NAMELater steps or dependent jobsNoTarget environment, list of changed specs
Next-generation test execution with TestMu AI

What's the Difference Between ${{ env.NAME }} and $NAME?

The two syntaxes are evaluated at different times. The GitHub guide on using variables states that contexts such as ${{ env.NAME }} are interpolated prior to the job being sent to the runner, whereas the shell on the runner will expand $NAME. That's why you "cannot use runner environment variables in parts of a workflow that are processed by GitHub Actions" (e.g. if:).

- if: ${{ env.TEST_BROWSER == 'firefox' }}   # evaluated by GitHub
  run: npx playwright test --project="$TEST_BROWSER"   # expanded by bash

GitHub's contexts reference adds two limits:

  • The env context works in any step key apart from id and uses.
  • It only contains the variables set in the workflow, job or step (not those the runner process inherits).

Default variables such as GITHUB_REF aren't in env. You need to read them as ${{ github.ref }} in expressions and as $GITHUB_REF in the shell.

How Do You Go About Debugging to Work Out Which Variables a Job Actually Sees?

Print the vars and env contexts with toJSON (the function that the contexts reference uses to pretty print the contexts to the log):

- name: Dump variables
  env:
    VARS_JSON: ${{ toJSON(vars) }}
    ENV_JSON: ${{ toJSON(env) }}
  run: |
    echo "$VARS_JSON"
    echo "$ENV_JSON"

Don't just dump the whole github context as that will contain github.token (GitHub's own docs make that very clear).

Do Environment Variables Get Passed to Reusable Workflows?

No. GitHub's reusable workflow reference states that environment variables set in an env context at the caller's workflow level "are not propagated to the called workflow".

Pass the values as inputs instead:

# caller
jobs:
  e2e:
    uses: ./.github/workflows/e2e-reusable.yml
    with:
      base-url: ${{ vars.BASE_URL }}

# .github/workflows/e2e-reusable.yml
on:
  workflow_call:
    inputs:
      base-url:
        type: string
        required: true

Configuration variables work differently. The variables reference states that reusable workflows will use the variables from the caller workflow's repository. The variables from the repository that contains the called workflow are not available.

Which Default Environment Variables Does GitHub Actions Provide?

GitHub sets these on every runner. These are the ones test pipelines use most:

VariableWhat it holds
CIAlways true, so test frameworks can tell CI from a laptop
GITHUB_SHACommit SHA that triggered the run
GITHUB_REF_NAMEShort branch or tag name
GITHUB_RUN_ID / GITHUB_RUN_NUMBERRun identifiers; unchanged on re-runs
GITHUB_RUN_ATTEMPTIncrements on each re-run, useful for labeling flaky tests
GITHUB_HEAD_REF / GITHUB_BASE_REFPR source and target branch (pull request events only)
GITHUB_WORKSPACEDefault working directory
RUNNER_OSLinux, Windows or macOS
RUNNER_TEMPTemp directory emptied at the start and end of each job

How Do Environment Variables Work on Windows Runners?

Windows runners default to PowerShell, so the syntax changes:

  • Read a variable as $env:NAME
  • In PowerShell 6+ (shell: pwsh), append to the environment file with "NAME=value" >> $env:GITHUB_ENV.
  • Windows PowerShell 5.1 (shell: powershell) doesn't write UTF-8 by default so GitHub's reference uses Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append.

To keep one workflow for all three operating systems, branch on runner.os:

- if: runner.os == 'Windows'
  run: 'echo "Browser: $env:TEST_BROWSER"'
- if: runner.os != 'Windows'
  run: 'echo "Browser: $TEST_BROWSER"'

What Are the Limits on GitHub Actions Variables?

The variables reference lists these limits for configuration variables:

  • 48 KB per variable.
  • Up to 1,000 organization variables (500 per repository, 100 per environment).
  • Org & repo variables share a 256KB total per workflow run. Environment variables don't count against that.
  • Names use letters, numbers and underscores only. They can't start with a number or with GITHUB_ and are case insensitive when referenced.

How Do You Pass In GitHub Actions Variables Into a HyperExecute Run?

HyperExecute reads its own hyperexecute.yaml, so the GitHub variables need one extra hop to get to the test machines.

The HyperExecute YAML reference documents three keys for this:

  • env sets environment variables on the HyperExecute machines.
  • vars are names and values that you can reference as ${name} elsewhere in the YAML.
  • strict: true will turn a variable that's missing from vars or the environment into an error rather than a warning.

The HyperExecute CLI reference has the --vars "key=value" flag, with one instance for each variable.

  • Create the variable per environment (add a BASE_URL variable to the staging and production environments in Settings > Environments).
  • Reference the environment and map the variable: set environment: staging on the job and map BASE_URL: ${{ vars.BASE_URL }} in the job's env.
  • Guard required values: add a step that runs : "${BASE_URL:?}" so that the job fails if the variable is empty.
  • Pass the value to the HyperExecute CLI: run the HyperExecute CLI with --user and --key from secrets and --vars "baseUrl=$BASE_URL".
  • Map it onto the test machines: in hyperexecute.yaml set strict: true and env: BASE_URL: ${baseUrl} so the tests read process.env.BASE_URL.
name: e2e-hyperexecute
on: [pull_request]
jobs:
  hyperexecute:
    runs-on: ubuntu-latest
    environment: staging
    env:
      BASE_URL: ${{ vars.BASE_URL }}
    steps:
      - uses: actions/checkout@v4
      - name: Check required variables
        run: |
          : "${BASE_URL:?Set BASE_URL as a variable on the staging environment}"
          curl --fail --silent --show-error --output /dev/null "$BASE_URL"
      - name: Label this run
        run: echo "RUN_LABEL=${GITHUB_REF_NAME}-${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}" >> "$GITHUB_ENV"
      - name: Download HyperExecute CLI
        run: |
          curl -fsSL -o hyperexecute https://downloads.lambdatest.com/hyperexecute/linux/hyperexecute
          chmod +x hyperexecute
      - name: Run tests on HyperExecute
        env:
          LT_USERNAME: ${{ secrets.LT_USERNAME }}
          LT_ACCESS_KEY: ${{ secrets.LT_ACCESS_KEY }}
        run: |
          : "${LT_USERNAME:?}" "${LT_ACCESS_KEY:?}"
          ./hyperexecute --user "$LT_USERNAME" --key "$LT_ACCESS_KEY" \
            --config hyperexecute.yaml \
            --vars "baseUrl=$BASE_URL" \
            --vars "runLabel=$RUN_LABEL" \
            --download-artifacts
# hyperexecute.yaml
version: 0.1
runson: linux
autosplit: true
concurrency: 2
strict: true
env:
  BASE_URL: ${baseUrl}
  RUN_LABEL: ${runLabel}
pre:
  - npm ci
  - npx playwright install chromium
testDiscovery:
  type: raw
  mode: local
  command: ls tests/*.spec.ts
testRunnerCommand: npx playwright test $test

Your tests then read process.env.BASE_URL exactly as they do on a laptop. Three checks stop a misconfigured run early:

  • The :? guard stops the job if either BASE_URL or a credential is empty.
  • curl --fail will stop it if the target returns an HTTP error.
  • strict: true causes a HyperExecute error on an unresolved ${baseUrl}.
HyperExecute run showing strict mode stopping a job when a YAML variable is missing.

The concurrency of 2 is the same as the free plan's 2 VMs. Playwright 1.65 can't install Chromium on HyperExecute's Linux image (Ubuntu 20.04, Node.js 18 by default), so pin @playwright/test to 1.55.0, which matches the Chromium build already cached there.

HyperExecute's CLI documentation makes no mention of whether the CLI will exit with a non-zero code when a test fails, but it exits with code 1 (Failed tasks found.) when one does, so the GitHub Actions step fails with it. Run one of the tests that is known to fail before you go relying on that step as a required PR check.

The older GitHub Actions integration doc just passes the credentials in as manual workflow inputs. The secrets-plus-env pattern shown above keeps the secrets completely out of the run form.

What Is the SCOPE Check for a Variable?

The SCOPE check is five questions to answer before you add a value to a workflow:

  • S - sensitive? If it actually mattered in the slightest, then make it a secret, not env or vars.
  • C - changes per target? If staging and production are different, then it should be an environment-level vars entry.
  • O - Just this workflow? If one workflow uses it and it's going to change as part of the code, then put it in env: at the most narrow block where you need it.
  • P - Produced at runtime? Write it to $GITHUB_ENV for later steps, or to $GITHUB_OUTPUT for other jobs.
  • E - Evaluated where? In if: and other keys that GitHub evaluates, use ${{ env.NAME }} or ${{ vars.NAME }}. Inside run: use $NAME.

Then add a guard such as : "${BASE_URL:?}" for every value a test can't possibly run without. An unset config variable resolves to an empty string rather than failing.

Watch: Environment Variables and GitHub Actions on the TestMu AI Channel

Setting environment variables in a test framework (Cypress, from the TestMu AI Cypress tutorial series):

Youtube thumbnail

A beginner walkthrough of running Cypress tests in a GitHub Actions workflow:

Youtube thumbnail

Conclusion

Pick each value's home with the SCOPE check, pass the runtime values via GITHUB_ENV or GITHUB_OUTPUT and guard all the values you need so that if any of them are missing, the job fails early.

Run the same variables on HyperExecute. Keep your workflow exactly as it is; just add one step and pass in the BASE_URL via --vars.

To run your first test, start free, or
for a full walkthrough of the product.

Was this helpful?

Authors

Anmol Gupta

Anmol Gupta

Author · 17 posts

Anmol Gupta is Vice President of Product Management at TestMu AI, driving HyperExecute, the test orchestration cloud that runs and accelerates automated test execution. He led the development of the Unified Test Execution Cloud Platform and now leads a 30-member cross-functional product organization across product lines contributing $7M+ in revenue. He brings over nine years of experience and previously co-founded the SaaS company Timble as CTO, where he grew the team from 5 to 40 and launched an AI KYC platform that processed 600K+ applications in five months while cutting verification time from 12 minutes to under 30 seconds. Anmol holds an MTech and BTech from IIT Delhi.

Mayank Bhola

Mayank Bhola

Reviewer

Mayank Bhola is Co-Founder and Head of Products at TestMu AI, where he leads the entire product portfolio across KaneAI, Kane CLI, HyperExecute, SmartUI, the Real Device Cloud, Accessibility, and other software testing product lines. As an early Lead Architect he designed and built the company's flagship Tunnel technology from scratch, created the React-based automation platform, and architected the data-intensive pipelines and FAAS services that scale it. He brings more than 10 years of experience in software development and product engineering, with earlier roles as Head of Technology at Juggernaut Books and Senior Software Engineer at PressPlay TV and Zomato. Mayank holds a B.Tech in Computer Engineering from JIIT Noida.

GitHub Actions Environment Variables FAQs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests