Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 78 ยท GitHub and Platforms

GitHub Actions: CI for Your Repository

Learn GitHub Actions: workflow YAML anatomy, triggers, jobs and steps, matrix builds, caching, secrets, artifacts and reusable workflows, with a runnable YAML sanity checker.

Continuous integration (CI) means that every change is built and tested automatically, on a clean machine, as soon as it is pushed. Nobody has to remember to run the tests, and nobody can say "it works on my computer". GitHub Actions is GitHub's built-in system for this: you describe what should happen in a YAML file inside your repository, and GitHub runs it on its servers whenever something happens (a push, a pull request, a schedule, a click on a button).

Actions can do much more than tests. They can build packages, publish releases, deploy a website, label issues or send a message. The same machinery runs all of it, so once you understand the structure you can read almost any workflow.

The sandbox has no GitHub and no network, so the workflow files in this lesson are read-only. To still practice, you will run real Bash code that checks a workflow file for common mistakes, expands a build matrix, computes cache keys and mimics how a job treats failing steps.

The anatomy of a workflow

A workflow is a YAML file in .github/workflows/. Here is a complete, typical one for a Node project. Read it from top to bottom first; the sections below explain each part.

YAML
name: CI                         # shown in the Actions tab

on:                              # WHEN to run
  push:
    branches: [main]
  pull_request:

permissions:                     # least privilege for the built-in token
  contents: read

jobs:                            # WHAT to run
  test:
    runs-on: ubuntu-latest       # the machine
    steps:
      - uses: actions/checkout@v4          # get the code
      - uses: actions/setup-node@v4        # install Node (+ cache npm downloads)
        with:
          node-version: 22
          cache: npm
      - run: npm ci                        # a shell command
      - run: npm test

(@v4 pins the major version of each action. Look up the current major version of an action on its repository page before you copy a workflow.)

The vocabulary:

  • Workflow: one YAML file.
  • Event: the thing that triggers a run (push, pull_request, ...).
  • Job: a group of steps that run on one fresh virtual machine (a runner). Jobs run in parallel unless you order them.
  • Step: one task inside a job, either run: (a shell command) or uses: (a reusable action).
  • Action: a packaged step written by GitHub or the community, versioned like software (actions/checkout@v4).
  • Runner: the machine that executes a job: GitHub-hosted (ubuntu-latest, windows-latest, macos-latest) or your own self-hosted machine.

Each job starts with an empty machine, so the first step is nearly always actions/checkout, which downloads your repository. Jobs do not share files; to pass data between jobs you use artifacts (below).

YAML in one minute

YAML is picky. Indentation (spaces only, never tabs) shows nesting, key: value is a mapping, and a line starting with - is a list item. A step is a list item whose keys (name, uses, run, with, env) are indented below it. Many first workflows fail for a wrong indent or a missing colon, so a quick sanity check before pushing saves a round trip. The script below checks the most common mistakes in every workflow file: tabs, a missing top-level on: or jobs:, jobs without runs-on: or steps:, uses: without a version, and - run npm test without the colon.

Bash A YAML sanity checker for workflow files

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The valid ci.yml printed OK. The broken file produced three findings with line numbers (a tab on line 5, uses: actions/checkout without @version on line 7, a missing colon after run on line 8) and FAIL, so the script exits with status 1, which is exactly what you want from a CI step or a pre-commit hook (Git Hooks). It is a heuristic, not a YAML parser, and it cannot know whether a key name is valid. For real validation use actionlint (a dedicated linter for workflow files) or the editor integration of your IDE. GitHub also reports syntax errors in the Actions tab when the workflow fails to start.

Triggers: the on key

on: lists the events that start the workflow. The most useful ones:

YAML
on:
  push:
    branches: [main]            # only pushes to main
    paths: ['src/**', 'package*.json']   # only if these files changed
    tags: ['v*']                # or a tag like v1.2.0
  pull_request:                 # when a PR is opened or updated
    branches: [main]
  schedule:
    - cron: '30 3 * * 1'        # every Monday 03:30 UTC
  workflow_dispatch:            # a "Run workflow" button in the web UI
  workflow_call:                # lets other workflows call this one

Notes:

  • pull_request runs on the merge result of the PR with the target branch and, for pull requests from forks, with a read-only token and no secrets. This is on purpose: strangers must not be able to steal your secrets by opening a PR.
  • schedule times are always UTC, can be delayed under load, and run only on the default branch.
  • A push to a branch with an open PR triggers both push and pull_request runs if you listed both. Restrict push to main as above to avoid doing the work twice.
  • paths filters save minutes in monorepos. Combine with required checks carefully: a check that never runs cannot report success.
  • Commit messages containing [skip ci] skip push and PR runs on GitHub.

Jobs, steps and the needs key

Jobs run in parallel by default. Use needs to order them, for example "deploy only after tests and lint passed":

YAML
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm run lint

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

  deploy:
    needs: [lint, test]
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - run: echo "deploying ${{ github.sha }}"

${{ ... }} is an expression. Inside it you can read contexts: github (event, branch, commit), env, secrets, matrix, needs, runner and others. The condition if: decides whether a job or step runs. Useful status functions are success() (the default), failure() and always().

How steps handle failure

Inside a job, steps run in order. When a step exits with a non-zero status, the remaining steps are skipped, except steps with if: always() (or failure()), which are meant for cleanup and for uploading logs. The next script mimics those rules so you can see them without a runner.

Bash Steps stop at the first failure, always() still runs

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Lint failed (the command test 1 -eq 2 is false), so Test was skipped, but Upload logs, marked like if: always(), still ran. The job as a whole failed with status 1, and that red cross is what shows up next to the commit and blocks the pull request when the check is required.

On the real service every run: step uses bash -e on Linux and macOS, so a failing command in a multi-line script ends the step. Pipelines still hide failures in the middle unless you use set -o pipefail or shell: bash (which enables pipefail) explicitly.

Matrix builds

A matrix runs the same job for every combination of some variables: operating systems, language versions, database versions. You write the job once and GitHub creates one job per combination.

YAML
jobs:
  test:
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false            # let the other combinations finish when one fails
      matrix:
        os: [ubuntu-latest, windows-latest]
        node: [20, 22, 24]
        exclude:
          - os: windows-latest
            node: 20
        include:
          - os: macos-latest
            node: 24
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
      - run: npm ci && npm test

Two operating systems times three versions is 6 combinations; exclude removes one and include adds another. You can see the result by expanding it yourself:

Bash Expanding a matrix by hand

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The matrix produces 6 jobs: five from the combinations after the exclusion plus one added by include. By default (fail-fast: true) the first failing job cancels the rest; set it to false when you want the full picture. Keep matrices small, because every job uses billable minutes on private repositories.

Caching dependencies

Installing dependencies from scratch on every run is slow. A cache stores a folder (such as npm's download cache) between runs under a key. If a cache with exactly that key exists, it is restored and the install is quick; if not, the job installs normally and saves a new cache at the end. The trick is a key that changes only when the dependencies change: the hash of the lock file.

YAML
- uses: actions/cache@v4
  with:
    path: ~/.npm
    key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
    restore-keys: |
      npm-${{ runner.os }}-

(Most setup actions, like setup-node with cache: npm, do this for you.) The logic of hashFiles can be shown with sha256sum:

Bash A cache key that follows the lock file

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The key stayed identical while the file did, which means a cache hit, and it changed the moment one dependency version changed (a miss). restore-keys is a fallback prefix: on a miss you still restore the most recent older cache and only fetch the difference. Caches are for things you can always rebuild; never store secrets or build results you need to trust in them. They are also evicted after a few days without use and have a size limit per repository.

Secrets and the built-in token

Workflows often need credentials: a deploy key, an npm token, a cloud login. Store them in Settings, Secrets and variables, Actions on GitHub (never in the repository), and read them with the secrets context:

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

Rules for secrets:

  • GitHub masks a secret's value in logs, but only if it matches exactly. Do not print secrets, transform them (base64, substrings) and then print the result, or write them to files that you upload as artifacts.
  • Secrets are not passed to workflows triggered by pull requests from forks.
  • Use variables (vars.NAME) for non-secret configuration.
  • Use environments (for example production) with required reviewers to protect deployment secrets.
  • Every run gets a short-lived GITHUB_TOKEN. Limit what it may do with the top-level permissions: key (contents: read for a test job). Prefer this to personal access tokens. For cloud deployments, prefer OpenID Connect (OIDC) logins over storing long-lived cloud keys.
  • Pin third-party actions to a full commit SHA (uses: owner/action@3f2a...), since a tag like @v4 can be moved by the author. GitHub's own actions are commonly pinned by major version.
  • Be careful with ${{ ... }} inside run: scripts: an issue title or branch name is user input, and pasting it into a shell command allows code injection. Pass it through env: and quote the variable instead.

See also Signing, Credentials and Security.

Artifacts and passing data between jobs

Each job runs on a fresh machine. To keep build outputs (test reports, a compiled binary, a coverage report) or hand them to a later job, upload them as artifacts:

YAML
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm run build
      - uses: actions/upload-artifact@v4
        with:
          name: site
          path: dist/
          retention-days: 7

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: site
          path: dist/
      - run: ls dist

Artifacts are listed on the run's summary page, so you can download them from the browser. For small values (a version number) use job outputs instead of files.

Reusable workflows and composite actions

When several repositories or workflows repeat the same steps, share them. A reusable workflow has on: workflow_call and optional inputs; callers use it like a function:

YAML
# .github/workflows/test.yml   (the reusable one)
on:
  workflow_call:
    inputs:
      node-version:
        type: string
        default: '22'
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ inputs.node-version }}
      - run: npm ci && npm test
YAML
# .github/workflows/ci.yml   (the caller)
on: [push, pull_request]
jobs:
  call-tests:
    uses: ./.github/workflows/test.yml
    with:
      node-version: '24'

A composite action (an action.yml with runs: using: composite) bundles several steps into one step. Use a reusable workflow to share whole jobs and a composite action to share a few steps.

Concurrency and required checks

Two settings make CI behave well on busy repositories:

YAML
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true      # a newer push cancels the older run of the same branch

And in branch protection you mark specific jobs as required status checks, so a pull request cannot be merged until they pass (Pull Requests and Code Review). Reference jobs by name, and keep job names stable.

Running workflows without GitHub

You cannot execute a workflow locally with plain Git, but the free tool act runs many workflows in Docker containers on your laptop, which shortens the edit-and-retry loop. It needs Docker, so it is read-only here:

CONSOLE
$ act -l                 # list the jobs found in .github/workflows
$ act pull_request       # run the jobs triggered by a pull_request event
$ act -j test            # run one job

Best practice: keep real logic in scripts inside the repository (./scripts/test.sh, make test) and let the workflow only call them. Then you can run exactly the same commands locally, in a Git hook, or on another CI system, and the YAML stays short.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do GitHub Actions workflow files live?

    Workflows are YAML files under .github/workflows/. They are versioned with your code.
  2. 2. A job has five steps and the third one fails. What happens to steps four and five by default?

    After a failing step the rest of the job is skipped, except steps whose if: condition says they should still run (always() or failure()).
  3. 3. What is the main purpose of a cache key such as npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}?

    When the lock file is unchanged the key matches and the cache is restored (a hit). A changed lock file gives a new key (a miss) and a fresh cache is saved.
  4. 4. A matrix has os: [ubuntu-latest, windows-latest] and node: [20, 22, 24], with no exclude or include. How many jobs run?

    A matrix is the cross product of its dimensions: 2 times 3 is 6 jobs.
  5. 5. Why do pull requests from forks not receive your repository's secrets?

    pull_request runs from forks get a read-only token and no secrets. Be very careful with triggers such as pull_request_target that do expose them.

Summary

  • A workflow is a YAML file in .github/workflows/: on: says when, jobs: says what. Jobs run in parallel on fresh runners; steps run in order and are either run: commands or uses: actions.
  • Start nearly every job with actions/checkout. Control order with needs, conditions with if:, and cleanup with if: always().
  • A matrix creates a job per combination (exclude and include adjust it); fail-fast: false lets the others finish.
  • Cache dependencies with a key based on the lock file hash; share outputs between jobs with artifacts.
  • Keep secrets in GitHub's secret store, limit the GITHUB_TOKEN with permissions:, pin third-party actions, and never paste untrusted input into shell commands.
  • Reusable workflows (workflow_call) and composite actions remove copy-paste. Put the real logic in repository scripts so you can run it anywhere.
  • Mark important jobs as required checks in branch protection so failing CI blocks merges.

Next: Issues, Projects and Project Management