Lab: Environment Variable Scope
Introduction
In this lab, you will learn how to set environment variables at different scopes, including workflow, job, and step levels. You will also learn how to access these environment variables in your workflow.
Estimated Duration: 20-30 minutes
Instructions
Step 1: Create a YAML Workflow File
-
In your repository, create a directory
.github/workflowsif it doesn’t exist. -
Inside
.github/workflows, create a new file namedenv-var-scope.yml. -
Add the following initial content to the file:
name: Env Var Scope on: workflow_dispatch: push: paths: - '.github/workflows/env-var-scope.yml' -
Commit the file to the
mainbranch.
Step 2: Add Environment Variable at Workflow Level
-
Edit
env-var-scope.ymland add a workflow-level environment variable calledWORKFLOW_ENV_VARwith the valueWorkflow Environment Variable:env: WORKFLOW_ENV_VAR: 'Workflow Environment Variable'
Step 3: Update the Workflow to Access and Print Environment Variables
- Add a job named
printthat runs onubuntu-latest. - Define a job-level environment variable
JOB_ENV_VARwith valueJob Environment Variable. - Add a step in the job where you define a step-level environment variable
STEP_ENV_VARwith valueStep Environment Variable. - Print the values of all three environment variables (
WORKFLOW_ENV_VAR,JOB_ENV_VAR, andSTEP_ENV_VAR).
The final workflow should look like this:
name: Env Var Scope
on:
workflow_dispatch:
push:
paths:
- '.github/workflows/env-var-scope.yml'
env:
WORKFLOW_ENV_VAR: 'Workflow Environment Variable'
jobs:
print:
runs-on: ubuntu-latest
env:
JOB_ENV_VAR: 'Job Environment Variable'
steps:
- name: Display Environment Variables
env:
STEP_ENV_VAR: 'Step Environment Variable'
run: |
echo "WORKFLOW_ENV_VAR: $WORKFLOW_ENV_VAR"
echo "JOB_ENV_VAR: $JOB_ENV_VAR"
echo "STEP_ENV_VAR: $STEP_ENV_VAR"
Step 4: Commit and Run the Workflow
- Commit the changes to the
mainbranch. - In GitHub, go to the Actions tab and select the Env Var Scope workflow.
- Click Run workflow and choose the
mainbranch. - After the workflow runs, review the logs to see the printed environment variable values.
Summary
Congratulations! You have successfully defined environment variables at different scopes (workflow, job, and step levels) and accessed them in your workflow. You have also learned how to print their values during workflow execution.