Master GitHub Actions with hands-on labs and exercises. Learn how to automate workflows, run tests, deploy applications, and more using GitHub's powerful automation platform. This repository has everything you need to get started with continuous integration and continuous deployment.
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
Navigate to the Environment Variable Scope Starter File.
Copy the content of the starter file:
name: Env Var Scope
on:
workflow_dispatch:
push:
paths:
- '.github/workflows/env-var-scope.yml'
In your repository, create a new workflow file under .github/workflows
and name it env-var-scope.yml
.
Paste the copied content into the new file.
Commit the workflow file to the main
branch.
env-var-scope.yml
file, define a new environment variable at the workflow level with the name WORKFLOW_ENV_VAR
and the value Workflow Environment Variable
.Add a job to your workflow with the name print
.
Inside the print
job, define the job-level environment variable JOB_ENV_VAR
and assign it the value Job Environment Variable
.
jobs:
print:
runs-on: ubuntu-latest
env:
JOB_ENV_VAR: 'Job Environment Variable'
Add a step inside the print
job and define the step-level environment variable STEP_ENV_VAR
with the value Step Environment Variable
.
In the step, print the values of the environment variables: WORKFLOW_ENV_VAR
, JOB_ENV_VAR
, and STEP_ENV_VAR
.
The final workflow should look like this:
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"
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"
Commit the changes to the main
branch.
Go to the Actions tab in your repository and locate the Env Var Scope workflow.
Trigger the workflow manually by clicking on the Run workflow button.
Once the workflow runs, check the logs to see the printed values of the environment variables.
Congratulations! You have successfully defined environment variables at different scopes (workflow, job, and step levels) and accessed them in your workflow. You’ve also learned how to print their values during the execution of the workflow.