Learn GitHub
$ gh ghautomation.ghactions

GitHub Actions and CI/CD

6 learning objectives · 12 key terms · 8 commands · 3 diagrams · 5 quiz questions

$objectives

GitHub Actions and CI/CD

Automation & Security

Module 4 of 5 · lesson 13 in this module

What you'll be able to do

  • Explain CI and CD and why automation changes a team’s release confidence
  • Write a workflow file and know where it must live in the repository
  • Use events, jobs, steps, runners and actions correctly
  • Pass configuration and secrets to a workflow without leaking them
  • Cache dependencies, upload artefacts and run matrix builds
  • Trigger workflows on a schedule or by hand, and gate a pull request on checks
$concept

The idea, in plain language

Continuous integration means every change is automatically built and tested as soon as it is pushed, so integration problems surface in minutes rather than at release time. Continuous delivery extends that to producing a deployable artefact on every green build, and continuous deployment goes one step further and ships it. GitHub Actions is the automation engine that runs all of it. A workflow is a YAML file in .github/workflows/; it declares what triggers it, what jobs to run, and what steps each job performs.

The execution model is worth internalising. An event (a push, a pull request, a schedule, a manual dispatch) starts a workflow run. Each job in the workflow runs on its own fresh virtual machine — a runner — so jobs are isolated and can run in parallel unless you explicitly declare needs. Within a job, steps run in order on the same machine, which is why checking out the code and installing language runtimes are steps rather than jobs. Each step is either a shell command (run:) or a reusable action (uses:) from the marketplace or another repository.

Two habits separate workflows that help from workflows that annoy. First, keep them fast: cache dependency directories and only run what the change affects. Second, treat secrets properly — repository or environment secrets are injected as environment variables or step inputs and are masked in logs, but a secret printed by a malicious script cannot be unmasked, so never echo them and never expose secrets to workflows triggered by fork pull requests.

$key terms

Key terms

Workflow
A YAML file in .github/workflows/ that defines one automated process.
Event / trigger
What starts a run — on: push, pull_request, schedule, workflow_dispatch, release and many more.
Job
A group of steps that run on one runner; jobs run in parallel by default.
Step
One run: shell command or one uses: action inside a job.
Runner
The fresh virtual machine a job executes on (ubuntu-latest, windows-latest, macos-latest, or self-hosted).
Action
A reusable unit of work, such as actions/checkout to clone the repository into the runner.
Secret
An encrypted value stored in repository security settings, injected at run time and masked in logs.
Artefact
A file produced by a job and kept for download or for a later job to consume.
Cache
Dependency data persisted between runs to cut install time.
Matrix build
Running the same job across a set of parameter combinations, such as three language versions.
Required status check
A workflow result that branch protection insists is green before merging.
workflow_dispatch
The trigger that adds a manual Run workflow button.
$steps

How it works, step by step

  1. 1
    Create the workflow directory

    The path is fixed: .github/workflows/ at the repository root, with a .yml or .yaml extension. Any file there is picked up automatically — no registration step.

    one-time setupbash
    mkdir -p .github/workflows
  2. 2
    Declare name and triggers

    Restrict triggers to the branches you care about, otherwise every scratch branch starts a run and the queue becomes noise.

    triggersyaml
    name: Run Tests
    
    on:
      push:
        branches: [main]
      pull_request:
        branches: [main]
      workflow_dispatch:
  3. 3
    Define a job and its runner

    Each job gets an id, a human-readable name, and the machine type it runs on. jobs.<id>.runs-on is required.

    jobyaml
    jobs:
      test:
        name: Unit tests
        runs-on: ubuntu-latest
  4. 4
    Write the steps in the order they must happen

    Check out the repository first, then install a runtime, then restore caches, then install dependencies, then run tests. Steps share the runner’s filesystem, so order matters.

    stepsyaml
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
    
      - name: Set up runtime
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
    
      - name: Install dependencies
        run: npm ci
    
      - name: Run tests
        run: npm test
  5. 5
    Pass configuration and secrets

    Use env: for plain configuration and secrets at the job or step level for anything sensitive. Reference a repository secret with the secrets context, and never echo it.

    env and secretsyaml
        env:
          NODE_ENV: test
        steps:
          - name: Publish coverage
            run: ./scripts/publish.sh
            env:
              COVERAGE_TOKEN: ${{ secrets.COVERAGE_TOKEN }}
  6. 6
    Keep runs fast with cache and matrix

    Caching dependency directories turns a three-minute install into ten seconds. A matrix runs the same job across several versions at once, catching compatibility problems early.

    matrixyaml
    strategy:
      fail-fast: false
      matrix:
        node: [18, 20, 22]
  7. 7
    Keep results and gate the merge

    Upload artefacts for anything you want to download later, and configure the workflow as a required status check so a red run blocks merging instead of being ignored.

    artefactsyaml
          - name: Upload coverage report
            uses: actions/upload-artifact@v4
            with:
              name: coverage
              path: coverage/
$commands

Commands worth memorising

Every block below is copy-ready — use the Copy button, then paste it into your terminal. Expected output is shown underneath so you know what “working” looks like.

list workflowsbash
gh workflow list
Output
Run Tests        active  25183446201  test.yml
Release          active  25183446202  release.yml

Confirms GitHub has picked up the files in .github/workflows/ and whether they are enabled.

recent runsbash
gh run list --limit 5
Output
✓  main        Run Tests  25183446201  1m12s
✕  feature/x   Run Tests  25183446177  48s

The quickest way to see whether main is currently green.

follow a run livebash
gh run watch
Output
✓ main Run Tests · 25183446201
  ✓ Set up job
  ✓ Checkout repository
  ✓ Run tests

Follows the latest run for the current branch and exits non-zero on failure.

read only the failurebash
gh run view --log-failed

Prints the failing step log alone. Far faster than paging through a whole run.

re-run what failedbash
gh run rerun 25183446177 --failed

Re-runs only the failed jobs, which is useful after a transient network error.

trigger by handbash
gh workflow run test.yml --ref feature/login

Requires workflow_dispatch in the workflow. Handy for testing workflow changes without an empty commit.

add a secretbash
gh secret set COVERAGE_TOKEN
Output
✓ Set Actions secret COVERAGE_TOKEN for ada/app

Reads the value from a prompt or stdin, so it never appears in your shell history. Use gh secret list to audit names only.

run history for one workflowbash
gh api repos/:owner/:repo/actions/workflows/test.yml/runs --jq '.workflow_runs[0:10] | .[] | .conclusion'
Output
"success"
"failure"
"success"

Useful for spotting flaky tests: a run of failures and successes on the same code is a signal.

$diagrams

Workflow diagrams

Diagram 1What happens when you push

The whole cycle is typically a couple of minutes, and the result is attached to the commit and the pull request.

Reading the diagram
  1. A push or pull request event matches the workflow’s on: filters and starts a run.
  2. Each job gets a fresh runner — nothing is left over from the previous run.
  3. Steps run in order on that machine: checkout, runtime setup, cache restore, install, test.
  4. The overall result appears on the commit and on the pull request, and can be required before merging.
Diagram 2How a workflow file is organised

Five keys cover the vast majority of real workflows.

Reading the diagram
  1. on: decides when; jobs: decides what; steps: decides how.
  2. Jobs run in parallel by default — add needs: when one must wait for another.
  3. Secrets are referenced through the secrets context and are masked in the logs.
Diagram 3CI and CD in one pipeline

Jobs are isolated, so build and deploy each start from a fresh machine and pass artefacts between them.

Reading the diagram
  1. The test job runs on every push and pull request and is the gate for everything after it.
  2. The build job declares needs: test, so it only starts when tests pass — and it starts on a fresh runner, so it downloads the test job’s artefacts rather than reusing files.
  3. The deploy job can require approval through an environment, which is how continuous delivery is kept safe.
  4. A failure anywhere in the chain leaves the later jobs skipped and the commit marked red.
$example

Worked example

A complete, beginner-friendly workflow: it tests on every push and pull request, caches dependencies, and uploads a coverage report.

.github/workflows/test.ymlyaml
name: Run Tests

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:

jobs:
  test:
    name: Test on Node ${{ matrix.node }}
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        node: [18, 20, 22]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up runtime
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test -- --coverage

      - name: Upload coverage report
        if: matrix.node == 20
        uses: actions/upload-artifact@v4
        with:
          name: coverage
          path: coverage/
Output
Actions tab shows 3 parallel jobs (Node 18, 20, 22). A green tick appears on the commit and on the pull request; a failure blocks a protected main branch.
1name: labels the workflow in the Actions tab — the first thing a teammate reads when a run fails.
2on: lists three triggers: pushes to main, pull requests targeting main, and a manual button via workflow_dispatch. Scratch branches do not start runs.
3jobs.test is the single job. runs-on: ubuntu-latest gives it a fresh Ubuntu virtual machine for the duration of the run.
4strategy.matrix runs the job three times, once per Node version. fail-fast: false means a failure on Node 18 does not cancel the other two, so you see the full compatibility picture.
5actions/checkout@v4 clones the repository into the runner — without it the machine is empty and npm has nothing to install.
6actions/setup-node@v4 installs the matrix Node version and its cache: npm setting caches the npm cache directory between runs, which typically cuts minutes off each run.
7npm ci installs exactly the locked dependency versions — reproducible, and faster than npm install in CI.
8The test step runs the suite with coverage. Any non-zero exit code fails the step, the job and the whole run.
9The final step uploads coverage, but only on the Node 20 job so you do not get three identical artefacts. Uploaded artefacts are downloadable from the run page for 90 days by default.
$use cases

Where you'll use it

▸Running the test suite on every pull request so a red build is visible before review begins.
▸Linting and formatting checks that keep a codebase consistent without human nagging.
▸Building and publishing a release artefact when a tag is pushed.
▸Deploying to a staging environment on merge to main, with production behind manual approval.
▸Scheduled dependency audits that open an issue when something needs attention.
▸Matrix builds that prove a library works across runtimes and operating systems.
$mistakes

Common mistakes

  • Printing secrets in logs — masked values can be revealed by transforms and encoded output.
  • Running workflows on every branch, so the queue fills with runs nobody wants.
  • Forgetting actions/checkout, then wondering why the workspace is empty.
  • Hard-coding dependency versions in the workflow instead of using the lockfile, so CI and production drift apart.
  • Exposing secrets to pull requests from forks, which is how credentials leak from public repositories.
  • Trusting third-party actions without pinning them to a version or commit SHA.
  • Letting a required check be flaky and then disabling it — a disabled check is worse than none.
$best practices

Best practices

  • Keep CI under about ten minutes; cache dependencies and run only what changed.
  • Pin actions to a major version at minimum, ideally a commit SHA, especially for third-party actions.
  • Make the test job a required status check on protected branches.
  • Store every credential in repository or environment secrets — never in the workflow file.
  • Use environments with required reviewers for production deploys.
  • Fail fast, but let matrix jobs finish (fail-fast: false) so you see the whole picture.
  • Upload logs and artefacts on failure so debugging does not require a re-run.
$exercise

Hands-on exercise

Add CI to one of your repositories

A green check on every push, then make it gate a merge.

  1. Create .github/workflows/ci.yml with a name, an on: block for push and pull_request to main, and a single job on ubuntu-latest.
  2. Add steps to checkout the repository, set up your language runtime, install dependencies and run your tests or linter.
  3. Push the workflow on a branch, open a pull request, and watch the run start in the Actions tab. Fix whatever fails first.
  4. Add cache support (for example, cache: npm on setup-node) and compare the run times before and after.
  5. Add a second job that depends on the first with needs:, and give it something useful to do such as building the project.
  6. Configure branch protection on main with the test job as a required status check, then deliberately break a test and confirm the merge button is blocked.

💡 Hint: You can re-run a failed workflow from the Actions tab, and workflow_dispatch adds a manual button so you do not need to push a commit to test changes to the workflow itself.

Done when: Every push to a branch in a pull request starts a workflow, the check appears on the pull request, and a failing test blocks the merge.

$quiz

Checkpoint quiz

0 of 5 answered · 0 correct

  1. Multiple choiceQ1

    Where must a workflow file live?

  2. Command outputQ2

    What does this job configuration do?

    strategy:
      matrix:
        node: [18, 20, 22]
  3. TroubleshootingQ3

    Your workflow fails immediately with "no such file or directory: package.json". The repository definitely contains it. What is the most likely cause?

  4. True or falseQ4

    True or false: secrets are safe to use in a workflow triggered by a pull request from a fork.

  5. Multiple choiceQ5

    What is the benefit of caching dependencies in a workflow?

$summary

Module summary

  • CI tests every change automatically; CD adds artefact production and deployment.
  • Workflows live in .github/workflows/ and are defined by on:, jobs:, steps:, env: and secrets:.
  • Jobs run on fresh runners and in parallel unless you chain them with needs:.
  • Checkout, set up the runtime, restore the cache, install, then test — in that order.
  • Secrets belong in repository or environment settings, never in the YAML, never echoed, never exposed to fork pull requests.
  • Cache, matrix and required status checks are what make CI fast enough and firm enough to trust.
  • Environments with required reviewers are how production deploys stay deliberate.

Next up: Automation runs unattended, which raises the stakes on what it can reach. Module 11 covers security: secrets management, scanning, branch protection and the dangerous commands to avoid.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Put the GitHub course to work: open one of the company-wise repositories and follow the workflow you just learned, branch to release.