Skip to content

Environment variables are crucial for passing data between steps and jobs in GitHub Actions workflows. Let’s dive into how to use them effectively.

GitHub Actions provides a set of default environment variables available in every workflow run. Some key ones include:

  • GITHUB_REPOSITORY: The owner/repo name
  • GITHUB_SHA: The commit SHA that triggered the workflow
  • GITHUB_REF: The branch or tag ref that triggered the workflow
  • GITHUB_WORKSPACE: The path to the GitHub workspace directory

For a full list, check out the official docs.

Set variables for all steps in a job using the env key:

jobs:
example-job:
runs-on: ubuntu-latest
env:
MY_VAR: value1
ANOTHER_VAR: value2
steps:
- name: Use job-level vars
run: echo $MY_VAR $ANOTHER_VAR

Set variables for a specific step:

jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Step with custom env
env:
STEP_VAR: step_value
run: echo $STEP_VAR

Adding custom environment variables from a step

Section titled “Adding custom environment variables from a step”

To set variables that persist across steps, use the GITHUB_ENV file:

jobs:
example-job:
runs-on: ubuntu-latest
steps:
- name: Set custom var
run: echo "CUSTOM_VAR=dynamic_value" >> $GITHUB_ENV
- name: Use custom var
run: echo $CUSTOM_VAR

Here’s a workflow that demonstrates various env var techniques:

name: Dynamic Config
on: [push]
jobs:
configure:
runs-on: ubuntu-latest
outputs:
env_name: ${{ steps.set-env.outputs.env_name }}
steps:
- name: Set environment name
id: set-env
run: |
if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then
echo "ENV_NAME=production" >> $GITHUB_ENV
echo "env_name=production" >> $GITHUB_OUTPUT
else
echo "ENV_NAME=staging" >> $GITHUB_ENV
echo "env_name=staging" >> $GITHUB_OUTPUT
fi
- name: Display env from previous step
run: |
echo "ENV_NAME from previous step: $ENV_NAME"
deploy:
needs: configure
runs-on: ubuntu-latest
env:
DEPLOY_ENV: ${{ needs.configure.outputs.env_name }}
steps:
- name: Deploy to environment
run: |
echo "Deploying to $DEPLOY_ENV"

This workflow:

  1. Sets an environment name based on the branch
  2. Passes the env name to a subsequent job
  3. Uses both job-level and step-level environment variables