Sub topic 2
Environment variables with env and their scope
This chapter covers the env keyword and how its scope decides which value a step sees. It assumes you know basic YAML, the workflow structure (on, jobs, runs-on, steps), and simple shell commands on a Linux runner.
What env does
An environment variable is a named value that the shell of a step can read, for example as $GREETING. In a workflow you set these variables with the env keyword. The runner places them in the process environment before it starts the step, so any command in that step can read them.
Plain env values are not expressions. A value such as hello from job is passed as written. You can also put ${{ }} expressions in env values. GitHub evaluates those first, and the shell then sees only the result. The next chapters cover expressions in detail.
Three scopes
You can set env at three levels:
- Workflow level: a top-level
envkey. Every job and step sees it. - Job level:
envunder a job. Every step in that job sees it. - Step level:
envunder a step. Only that step sees it.
When the same name appears at more than one level, the most specific scope wins. A step value overrides a job value, and a job value overrides a workflow value.
name: env-scopes
on: push
env:
GREETING: hello from workflow
jobs:
show:
runs-on: ubuntu-latest
env:
GREETING: hello from job
steps:
- name: Job-level value
run: echo "$GREETING"
- name: Step-level value
env:
GREETING: hello from step
run: echo "$GREETING"The first step prints hello from job, because the job value replaces the workflow value. The second step prints hello from step. The override applies only to that step. A third step with no env would print hello from job again.
Common errors
- Expecting a job-level
envto be visible in another job. Each job runs on its own runner, so values do not carry across jobs. Use job outputs for that, which a later chapter covers. - Setting
envat the step level and expecting the next step to see it. Step scope ends with the step. - Using the wrong syntax to read a value. In a
runscript,$GREETINGis read by the shell. The form${{ env.GREETING }}is read by GitHub before the shell starts. Both work in arunscript, but they behave differently, and the difference matters for security later in this tutorial. - Using a name that starts with
GITHUB_. The runner reserves these names for its own variables, and you cannot reliably override them.
Check your understanding
Exercise
A workflow sets env: { MODE: test } at workflow level and env: { MODE: build } at job level. Step 1 has no env. Step 2 sets env: { MODE: deploy }. Step 3 has no env. What does echo "$MODE" print in each of the three steps?
Show answer
Step 1 prints build, because the job value overrides the workflow value. Step 2 prints deploy, because the step value is the most specific. Step 3 prints build again, because the step-level value applies only to step 2.