Default Environment Variables
GitHub Actions provides a set of default environment variables available in every workflow run. Some key ones include:
GITHUB_REPOSITORY
: The owner/repo nameGITHUB_SHA
: The commit SHA that triggered the workflowGITHUB_REF
: The branch or tag ref that triggered the workflowGITHUB_WORKSPACE
: The path to the GitHub workspace directory
For a full list, check out the official docs ↗.
Setting Environment Variables
Job-level Variables
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
Step-level Variables
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
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
Practical Example: Dynamic Configuration
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:
- Sets an environment name based on the branch
- Passes the env name to a subsequent job
- Uses both job-level and step-level environment variables