Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 44 ยท Practice and Review

Practice: Pipeline Exercises with Solutions

Test your CI/CD skills with ten graded pipeline exercises: fix broken YAML, write matrices, cache keys, needs graphs, gating rules and secret handling.

Reading about pipelines is one thing; spotting the bug in a broken one is another. This lesson gives you ten exercises, from easy to hard, each with a short problem, a hint and a full solution. They revisit the core skills of the tutorial: reading YAML, matrices, caching, dependency graphs, gating deployments and handling secrets.

Real workflows cannot run on this site, so the YAML in the exercises is read-only. To still give you instant feedback, four stand-in checkers (small JavaScript programs) model the core logic: a matrix expander, a cache key lookup, a needs graph validator and a pipeline text linter. Use them to test your answers before you read the solutions. Try each exercise on paper first; the learning is in the attempt.

How to use the exercises

  1. Read the problem and write your own answer.
  2. Use the checker if the exercise has one.
  3. Open the solution and compare, paying attention to the explanation, not just the final text.

Difficulty is marked from one star (easy) to three stars (hard).

Exercise 1 (one star): fix the broken YAML

This workflow is rejected. Find three problems.

YAML
name: CI
on:
  push:
    branches: [main]
jobs:
  test:
  runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run npm test

Hint: read the indentation of runs-on, and look for the missing character on the last line.

Solution. Three problems. First, runs-on sits at the same indentation as test:, so it is read as a second job name instead of a key of test, and the indented steps under it cannot be parsed at all. Second, steps must be indented at the same level as runs-on. Third, - run npm test lacks the colon after run, so it is a plain string and not a mapping with a command. Corrected:

YAML
name: CI
on:
  push:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

Related lessons: YAML for Pipeline Authors and Your First Workflow.

Exercise 2 (one star): write a matrix

Test on Node 18, 20 and 22, on both Ubuntu and Windows. Windows with Node 18 should be skipped. Also add one extra job for Node 24 on Ubuntu, marked experimental. How many jobs run?

Hint: multiply the axes, subtract exclude matches, then see whether include adds a new combination.

Solution. Six combinations from the axes, minus one excluded gives five, plus one included gives six:

YAML
strategy:
  fail-fast: false
  matrix:
    os: [ubuntu-latest, windows-latest]
    node: [18, 20, 22]
    exclude:
      - os: windows-latest
        node: 18
    include:
      - os: ubuntu-latest
        node: 24
        experimental: true
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental == true }}

The include entry does not match any existing combination (Node 24 is not on the axis), so it becomes a new job. Setting continue-on-error from the matrix value keeps an experimental failure from failing the run. See Matrix Builds.

Checker 1: the matrix expander

Paste your own axes into the checker to count jobs. It follows the rules above: exclude removes matching combinations from the axes, and include either adds keys to matching combinations or creates a new one.

JS Matrix expander

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

No output.

The checker prints six jobs, the last being the experimental one. Try removing exclude (seven jobs, with the extra Windows/Node 18) or adding include: [{ os: "ubuntu-latest", coverage: true }], which has no node key and therefore decorates every Ubuntu job instead of adding a new one.

Exercise 3 (two stars): design a cache key

A Node project installs dependencies with npm ci. You want to cache ~/.npm. Write the cache step so a lockfile change creates a new cache, but an older cache is still used as a starting point.

Hint: use hashFiles in the key and a shorter prefix in restore-keys. Include the operating system.

Solution.

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

An exact key hit restores the cache and skips saving. On a miss, the prefix in restore-keys finds the newest cache that begins with npm-Linux-, which gives npm ci a warm start, and the new cache is saved under the exact key at the end of the job. Including runner.os stops a Linux cache from being used on Windows. Most setup-* actions can do this for you with cache: npm. Details: Caching and Artifacts.

Checker 2: the cache lookup

This model stores existing cache entries (oldest to newest) and resolves a request the way the cache action does: exact key first, then each restore-keys prefix, taking the newest match.

JS Cache key lookup

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

No output.

The second request misses exactly, but falls back to the newest Linux entry. The last one has no restore-keys, so it finds nothing. This is why a cache key that includes a hash and has no fallback always starts cold after any dependency change.

Exercise 4 (two stars): the needs graph

You have jobs lint, test, build, deploy and notify. Requirements: lint and test run in parallel; build needs both; deploy needs build and runs only on main; notify always runs after deploy, even if it fails or was skipped. Write the dependency lines.

Solution.

YAML
jobs:
  lint:   { runs-on: ubuntu-latest, steps: [{ run: echo lint }] }
  test:   { runs-on: ubuntu-latest, steps: [{ run: echo test }] }
  build:
    needs: [lint, test]
    runs-on: ubuntu-latest
    steps: [{ run: echo build }]
  deploy:
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps: [{ run: echo deploy }]
  notify:
    needs: [build, deploy]
    if: ${{ always() }}
    runs-on: ubuntu-latest
    steps: [{ run: echo "deploy was ${{ needs.deploy.result }}" }]

Without always(), notify would be skipped whenever deploy is skipped on a feature branch. Listing build as well makes its result available. See Jobs, Steps and Dependencies.

Checker 3: the needs graph validator

Describe your jobs as a graph and the validator reports unknown dependencies, cycles and the order of waves.

JS needs graph validator

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

No output.

Exercise 5 (two stars): gating a deployment

The deploy job must run only for pushes to main on the original repository, never for pull requests from forks and never for tag pushes. It must wait for approval from the production environment. Write the job header.

Solution.

YAML
deploy:
  needs: build
  if: github.event_name == 'push' && github.ref == 'refs/heads/main'
  runs-on: ubuntu-latest
  environment: production
  concurrency:
    group: deploy-production
    cancel-in-progress: false

A push event on refs/heads/main excludes pull requests and tags. Fork pull requests run in the pull_request event and have no access to secrets anyway, but the explicit condition documents the intent. environment: production applies required reviewers and environment-scoped secrets, and the concurrency group queues deployments one at a time. See Environments, Approvals and Deployments.

Exercise 6 (three stars): fix the secret handling

Find all the problems in this step and rewrite it.

YAML
on: pull_request_target
jobs:
  comment:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
      - run: |
          echo "Title: ${{ github.event.pull_request.title }}"
          echo "Token is ${{ secrets.API_TOKEN }}"
          ./scripts/check.sh

Hint: there are four distinct issues.

Solution. The problems:

  1. pull_request_target runs with secrets and a write token, and the job checks out and executes untrusted code from the pull request. That is the classic way to leak secrets.
  2. The pull request title is pasted into the script with ${{ }}, which allows script injection.
  3. Echoing a secret prints it in the log (masking helps, but encoded or split values can slip through).
  4. The workflow has no permissions block, so the token may be broader than needed.

A safer version uses the plain pull_request trigger for anything that runs the author's code, and passes data through the environment:

YAML
on: pull_request
permissions:
  contents: read
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - env:
          TITLE: ${{ github.event.pull_request.title }}
        run: |
          echo "Title: $TITLE"
          ./scripts/check.sh

If a job truly needs a write token for pull requests from forks (for example to comment), split it: run the untrusted code in a pull_request workflow, upload results as an artifact, and let a separate trusted workflow post the comment without executing that code. Read Secrets, Variables and Environment Variables and Securing Your Pipeline.

Checker 4: the pipeline linter

This small linter looks for three of the problems above in workflow text. It is a rough pattern matcher for teaching, not a replacement for real security scanners.

JS Simple workflow linter

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

No output.

Exercise 7 (two stars): stop wasting runs

Pushing five commits to a pull request in ten minutes starts five full runs. Only the latest matters. Add the setting, but make sure it never cancels runs on main.

Solution.

YAML
concurrency:
  group: ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}

The group is per workflow and branch, so different branches never cancel each other. The expression makes cancellation conditional, so deployments from main finish. Related: CI for Node and Python Projects.

Exercise 8 (two stars): the GitLab rules question

In GitLab, a job should run in merge request pipelines and on the default branch, but not for ordinary branch pushes. Write the rules.

Solution.

YAML
test:
  script: npm test
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

A job with rules is added to the pipeline only if one rule matches, so a push to a feature branch matches neither and the job is absent. Review Rules, needs, Artifacts and Cache.

Exercise 9 (three stars): the Jenkins branch rule

In a Jenkins declarative pipeline, the Deploy stage must run only on main, must not start an agent for other branches, and the pipeline must send mail only when a build goes from passing to failing.

Solution.

GROOVY
stage('Deploy') {
  when {
    beforeAgent true
    branch 'main'
  }
  agent { label 'deploy' }
  steps { sh './deploy.sh' }
}
// at the end of the pipeline:
post {
  regression {
    mail to: '[email protected]', subject: "Regression in ${env.JOB_NAME}", body: env.BUILD_URL
  }
}

beforeAgent true evaluates when first, so no executor is reserved for skipped branches. regression fires only when the previous build was successful and this one is not, which avoids a mail for every failing build in a row. See The Declarative Jenkinsfile.

Exercise 10 (three stars): design question

A pipeline takes 28 minutes: install (3), lint (2), unit tests (10), integration tests (8), build (3), all sequential. Propose a redesign and estimate the new time.

Solution. Install once and cache; run lint, unit tests and integration tests in parallel (each after a cached install, about one minute); build in parallel too, or only after tests if you must not build failing code. The critical path becomes install (1) plus the longest parallel job. If unit tests are split into two shards, the longest job drops to 8 minutes from integration tests. Total: about 9 to 10 minutes. The trade-off is more runner minutes used overall for less waiting. See Making Pipelines Fast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A matrix has os: [ubuntu, windows] and node: [18, 20, 22] with no exclude or include. How many jobs run?

    Two operating systems times three Node versions give six combinations.
  2. 2. Why does restore-keys help when a lockfile changes?

    The exact key misses after a change, so the prefix finds an older, mostly valid cache to reduce install time.
  3. 3. Which trigger is most dangerous when combined with checking out the pull request head and running its scripts?

    pull_request_target runs in the context of the base repository, with secrets and write permission, so running untrusted code there can leak them.
  4. 4. How do you let a notify job run even when deploy was skipped?

    The default condition is success(), so a skipped dependency skips the job. always() overrides it.
  5. 5. In GitLab, what happens to a job whose rules list matches nothing?

    With rules, a job exists only if a rule matches. No match means the job is absent.

Summary

  • Most YAML failures are indentation, a missing colon or a misplaced key; read structure before content.
  • Matrix size is the product of the axes, minus exclude, plus new include combinations.
  • Cache keys combine the OS and a lockfile hash; restore-keys prefixes provide warm starts.
  • needs creates waves; use always() for notifications and cleanup.
  • Gate deployments by event, branch, environment and concurrency; keep secrets out of logs and untrusted text out of scripts.
  • Faster pipelines come from parallelism and caching on the critical path.
  • The checkers on this page are models for practice, not real validators.

Next: Common CI/CD Mistakes and Anti-Patterns