Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 44 ยท GitHub Actions Basics

Expressions and Contexts

Master the ${{ }} syntax in GitHub Actions: the github, env, vars, secrets, matrix and needs contexts, built-in functions and status checks like always().

A workflow file is mostly static YAML, but real pipelines must react to things that are only known at run time: which branch was pushed, which matrix entry is running, what the previous job returned. Expressions are the small language GitHub Actions uses for this. You write them between ${{ and }}, and the values they read come from contexts, which are named objects such as github, matrix and needs.

You met a few expressions in Jobs, Steps and Dependencies. This lesson explains the whole idea: where expressions are evaluated, which contexts exist, the functions you will use daily, and the status functions that decide whether a step runs after a failure. The workflow snippets are read-only. The runnable example is a stand-in: a small evaluator that follows the same rules for literals, operators and a few functions. It is not GitHub's engine.

The ${{ }} syntax

Anything inside ${{ }} is evaluated by GitHub before the step runs. The result is turned into text and pasted into the YAML value, so by the time a shell sees it, it is just a string.

YAML
steps:
  - name: Greet
    run: echo "Hello from ${{ github.actor }} on ${{ github.ref_name }}"

  - name: Only on main
    if: github.ref == 'refs/heads/main'
    run: echo "main branch"

Notice the second step. In an if condition, you may leave out ${{ }} because the whole value is already an expression. There is one trap: a YAML value that starts with ! is a YAML tag, not an expression, so a negated condition needs the braces or quotes: if: ${{ !cancelled() }}.

Expressions are allowed in many places (name, env, with, run, if, runs-on, matrix), but not everywhere, and not every context is available everywhere. For example, the secrets context cannot be used directly in an if; copy the secret into an environment variable and test that instead. The official context-availability table is long, so remember the rule of thumb: values known early (the event, the repository) work nearly everywhere, while values created late (step outputs, job results) work only after that point exists.

The main contexts

A context is a read-only object. You reach inside with dots (github.sha) or brackets (github['sha']).

Context What it holds Example
github Event, repository, ref, SHA, actor, run ids github.event_name, github.sha
env Variables set with env: in the workflow, job or step env.NODE_ENV
vars Configuration variables from repository, environment or organization settings vars.DEPLOY_REGION
secrets Encrypted secrets, plus secrets.GITHUB_TOKEN secrets.NPM_TOKEN
job Info about the running job, such as its status job.status
steps Outputs and outcomes of earlier steps in this job steps.build.outputs.path
runner The machine: operating system, architecture, temp dir runner.os
matrix The current matrix combination matrix.node
needs Results and outputs of jobs listed in needs needs.build.outputs.version
inputs Inputs of workflow_dispatch or workflow_call inputs.environment

Two details deserve attention. First, env and the shell's environment are different things. ${{ env.NAME }} is resolved by GitHub before the step starts, while $NAME in a run script is resolved by the shell while it runs. Second, each steps.<id> entry has an outputs map and also two status fields, outcome (before continue-on-error is applied) and conclusion (after).

flowchart LR
  E["push event"] --> G["github context"]
  S["Settings: vars and secrets"] --> V["vars / secrets contexts"]
  M["strategy.matrix"] --> X["matrix context"]
  J["earlier jobs"] --> N["needs context"]
  G --> EX["Expression<br/>in YAML"]
  V --> EX
  X --> EX
  N --> EX
  EX --> R["Resolved text<br/>in the step"]

Contexts feed expressions; GitHub replaces each expression with its result before the step runs.

Literals, operators and truthiness

Expressions support a small set of literals: booleans (true, false), null, numbers (42, 3.5) and strings in single quotes ('text'). Double quotes are not string delimiters here, which surprises many beginners. To put a single quote inside a string, double it: 'it''s'.

The operators are !, &&, ||, comparisons (<, <=, >, >=), == and !=, plus parentheses for grouping. Three behaviours are different from what you may expect from other languages:

  • String comparison ignores case: 'Main' == 'main' is true.
  • == is loose: when the types differ, both sides are converted to numbers first, so '1' == 1 is true, while 'false' == false is not (the text has no numeric value).
  • && and || return values, not just booleans. a || b yields a if it is truthy, otherwise b. That makes github.ref_name || 'none' a handy default.

The falsy values are false, 0, -0, '' (empty string) and null. Everything else, including the string 'false', is truthy. That last point causes real bugs: an input of type string holding 'false' is true in an if. Compare it explicitly: inputs.dry_run == 'false'.

Reading a property that does not exist does not crash. It evaluates to null. This helps (an optional property just becomes falsy) and hurts (a typo silently never matches). When a condition seems dead, print the context with toJSON in a debug step.

Functions you will use daily

YAML
steps:
  - if: contains(github.event.head_commit.message, '[skip deploy]') == false
    run: ./deploy.sh

  - if: startsWith(github.ref, 'refs/tags/v')
    run: echo "release tag"

  - run: echo "key=${{ format('{0}-{1}', runner.os, matrix.node) }}"

  - run: echo '${{ toJSON(github.event.pull_request.labels.*.name) }}'
  • contains(search, item) works on strings (substring, case-insensitive) and on arrays (membership).
  • startsWith and endsWith check the beginning or end of a string.
  • format('{0} {1}', a, b) fills numbered placeholders.
  • join(array, separator) glues array items together.
  • toJSON(value) and fromJSON(text) convert between objects and text. fromJSON is what lets one job generate a matrix for another.
  • hashFiles('**/package-lock.json') returns a hash of the matching files, so a cache key changes exactly when the lock file changes. It is covered in Caching and Artifacts.
  • An asterisk filter such as labels.*.name collects a property from every item of an array.

Be careful when you paste untrusted values such as a pull request title into a run: line with ${{ }}. The text is inserted before the shell parses it, which is an injection risk. Securing Your Pipeline shows the safe pattern: put the value in env: and use the shell variable.

Status check functions

By default a step has an implicit success() condition: it runs only if every previous step succeeded. Four functions change that:

Function True when
success() no earlier step failed or was cancelled (the default)
failure() an earlier step or a needed job failed
cancelled() the workflow run was cancelled
always() always, even after cancellation
YAML
steps:
  - run: npm test
  - name: Upload logs on failure
    if: failure()
    uses: actions/upload-artifact@v4
    with:
      name: test-logs
      path: logs/
  - name: Clean up
    if: always()
    run: ./cleanup.sh

Prefer !cancelled() over always() for cleanup that should still stop when someone cancels the run, because always() keeps running even then and can hold up the cancellation.

Stand-in: a mini expression evaluator

The model below tokenizes an expression, parses it with the precedence rules above and evaluates it against a sample context. It has case-insensitive string comparison, loose number comparison, value-returning &&/||, null for missing properties and a handful of functions. Edit the expressions list and try your own. The real engine has more functions and stricter rules, so treat this as a learning model.

JS Mini expression evaluator

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

No output.

Look at the two inputs.dry_run lines. The first returns the text "false", which an if treats as truthy. The second compares it with the boolean false: the text becomes a number that is not a number, so the comparison is false too. Neither behaves the way the word suggests. That is why workflows compare inputs with a string, such as inputs.dry_run == 'false', instead of relying on truthiness.

A second model: the status functions

The next example models the implicit success() rule for a list of steps. Each step has a condition (default, failure, always). The runner tracks whether anything failed so far and decides which steps run.

JS Which steps run after a failure?

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

No output.

Build is skipped because the implicit success() is false after Test. Upload logs runs only because something failed, and Clean up runs regardless.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which string literal is valid in a GitHub Actions expression?

    Strings use single quotes. To include a single quote inside, double it. Double quotes and backticks are not string delimiters in expressions.
  2. 2. An input holds the string 'false'. What does the condition if: inputs.flag do?

    Only false, 0, -0, an empty string and null are falsy. The text 'false' is a non-empty string, so compare explicitly with == 'false'.
  3. 3. You want a log-upload step to run only when an earlier step failed. Which condition fits?

    failure() is true when an earlier step or needed job failed. always() would also upload on success, and success() is the default.
  4. 4. What does github.some.missing.property evaluate to?

    Missing properties yield null instead of an error. That is convenient, but it also means a typo in a condition can silently never match.
  5. 5. Why can a value inside ${{ }} in a run script be dangerous with untrusted input?

    GitHub substitutes the result into the script text first. A crafted pull request title can therefore become shell code. Pass it through env instead.

Summary

  • ${{ }} expressions are evaluated by GitHub before a step runs; in an if the braces are optional, except when the value starts with !.
  • Contexts such as github, env, vars, secrets, steps, matrix, needs and inputs supply the data; availability depends on where in the file you are.
  • Strings use single quotes, comparison of strings ignores case, == is loose, and &&/|| return values; null, false, 0 and '' are falsy.
  • Daily functions are contains, startsWith, format, join, toJSON, fromJSON and hashFiles.
  • success() is the implicit default; use failure(), always() or !cancelled() to run steps after problems.

Next: Matrix Builds