# GitHub Actions: your first real pipeline

How GitHub Actions turns an event into jobs on a runner: the YAML you need, the triggers that matter, jobs and steps, what a runner gives you, and checking a workflow before you push it.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 2. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/cicd/02-github-actions-basics

## What you will learn

- Explain how an event becomes a workflow run, with jobs on runners and steps inside them
- Write the YAML a workflow needs, and avoid the type traps that break pipelines
- Choose triggers (push, pull_request, workflow_dispatch, schedule) and filter them by branch and path
- Order jobs with needs, and know what jobs do and don't share
- Pick a GitHub-hosted runner and know what's already installed on it
- Check a workflow with actionlint before pushing it

## How an event becomes a run

Before workflow automation, a developer had to remember to run the same checks before every merge. Miss one, and
broken code can reach the main branch. GitHub Actions turns those steps into a workflow file. A repository event
starts a run, jobs execute on runners, and each job performs its steps in order. In this lesson, you'll create
that file for shop-api and see how a failed check blocks later work.

> **Figure.** How GitHub Actions works. An event, such as a push to main or a pull request, starts a run of every workflow in .github/workflows that listens for it. The workflow ci.yml has two jobs. Job lint and job test each get their own fresh runner, an ubuntu-latest virtual machine. test has needs: lint, so it waits for lint to pass. Inside each job, steps run in order: checkout the code, set up Node, then run a command. If any step fails, the job fails, later steps are skipped, and the pull request shows a red check.
>
> Event → workflow run → jobs, each on its own fresh runner → steps in order. A failing step fails the job.

Every lesson in this course builds the same small app, **shop-api**: a Node.js service with a
`/health` endpoint, a `/price` endpoint that adds tax, and tests that use Node's built-in test runner.
No dependencies to install, so the pipeline is the only thing you're learning:

```sh
$ npm run lint && npm test
✔ adds 18% tax and rounds to cents
✔ rejects a negative amount
✔ GET /health answers ok
ℹ tests 3
ℹ pass 3
ℹ fail 0
```

Here's its first pipeline. Save it as `.github/workflows/ci.yml`:

```yaml
name: CI

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

jobs:
  lint:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 22
      - run: npm run lint

  test:
    needs: lint
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 22
      - name: Run the tests
        run: npm test
```

> **Video.** [GitHub Actions Explained: Everything You Need to Know](https://www.youtube.com/watch?v=xO5P-tu4a_4&t=225s) (DevOps with Flavius)

## The YAML you need

Workflows use a small part of YAML. Indentation is structure: **two spaces, never tabs**.

| You write                     | YAML means                         | Used for                      |
| ----------------------------- | ---------------------------------- | ----------------------------- |
| `key: value`                  | a mapping                          | `runs-on: ubuntu-latest`      |
| `- item`                      | a list item                        | each step                     |
| `[a, b]`                      | a list on one line                 | `branches: [main, release/*]` |
| `run: \|` then indented lines | a multi-line string, newlines kept | scripts of several commands   |
| `# text`                      | a comment                          | explaining why                |

```yaml
- name: Build and smoke-test
  run: |
    npm run build
    node dist/server.js &
    sleep 2 && curl -fsS http://localhost:3000/health
```

> **YAML guesses types, and guesses wrong.** `python-version: 3.10` is read as the **number 3.1**, so you get the wrong Python or a failed step. `node-version: 22` is fine, but quote any version with a dot: `"3.10"`, `"1.20"`. Values like `yes`, `no`, `on` and `off` can also turn into true or false in some tools, so quote strings that look like them. actionlint doesn't catch the version trap, so it's on you.

## Triggers: when a workflow runs

The `on:` block lists the events. These five cover almost every pipeline:

```yaml
on:
  push:
    branches: [main]            # pushes to main only
    paths-ignore: ['**.md']     # skip runs for documentation-only changes
  pull_request:                 # every PR, on open and on each new push to it
    branches: [main]            # …targeting main
  workflow_dispatch:            # a "Run workflow" button, and gh workflow run
    inputs:
      environment:
        type: choice
        options: [staging, production]
  schedule:
    - cron: '30 22 * * *'       # 22:30 UTC = 04:00 IST, every day
  release:
    types: [published]          # when a GitHub Release is published
```

| Event               | Typical use                                                        |
| ------------------- | ------------------------------------------------------------------ |
| `pull_request`      | the checks that gate merging: lint, test, build                    |
| `push` to `main`    | build the artifact, deploy to staging                              |
| `workflow_dispatch` | manual deploys, one-off maintenance                                |
| `schedule`          | nightly security scans, cleanup, dependency checks                 |
| `release`           | deploy to production (the Git course's _Tags and releases_ lesson) |

`schedule` uses **UTC**, and scheduled runs can start several minutes late when GitHub is busy. They
also stop after 60 days without activity in a public repository. Start a dispatch workflow from the
terminal with `gh workflow run ci.yml`.

> **Video.** [Mastering GitHub Actions Triggers | Push, Pull Requests, Schedule & Manual Workflows](https://www.youtube.com/watch?v=izzUdpIKda0) (The DevOps Toolkit)

## Jobs and steps

A **job** is a set of steps that run on one runner. Jobs run **in parallel** unless `needs:` says
otherwise:

```yaml
jobs:
  lint:    { runs-on: ubuntu-latest, steps: [...] }
  test:    { needs: lint, runs-on: ubuntu-latest, steps: [...] }   # waits for lint
  build:   { needs: [lint, test], runs-on: ubuntu-latest, steps: [...] }
```

A **step** does one of two things:

| Step    | Runs                                           | Example                     |
| ------- | ---------------------------------------------- | --------------------------- |
| `uses:` | a reusable **action**, configured with `with:` | `uses: actions/checkout@v7` |
| `run:`  | shell commands on the runner (bash on Linux)   | `run: npm test`             |

Each step must succeed (exit code 0) for the next one to run. When one fails, the job fails, the rest of
its steps are skipped, and jobs that `need` it are skipped too.

> **Jobs don't share a disk.** Each job starts on a brand-new machine with an empty folder, which is why both jobs above check out the code and set up Node. To pass files from one job to another, upload them as an **artifact** (the *Workflow details* lesson). `timeout-minutes` matters too: the default is 360 minutes, and a hung test would burn six hours of runner time.

## Runners: where jobs run

A **runner** is the machine a job runs on. GitHub-hosted runners are fresh virtual machines, created
for each job and destroyed after it:

| `runs-on:`       | Machine            | Notes                                                              |
| ---------------- | ------------------ | ------------------------------------------------------------------ |
| `ubuntu-latest`  | Linux VM           | the default choice: fastest to start, cheapest                     |
| `windows-latest` | Windows VM         | for Windows builds; costs more minutes than Linux on private repos |
| `macos-latest`   | macOS VM           | for iOS and Mac builds; the most expensive minutes                 |
| `ubuntu-24.04`   | pinned Linux image | use a fixed version when `-latest` moving would break you          |

The images come with Git, Docker, Node, Python, Java, the cloud CLIs and much more preinstalled (the
full list is linked below). Public repositories get free minutes; private ones get a monthly allowance
on each plan. The _Scaling pipelines_ lesson covers self-hosted runners, for when you need your own
hardware or network access.

## Check it before you push

A typo in a workflow is found only after you push, wait and read a red run. **actionlint** finds most
of them in under a second, on your machine. Here it is on a deliberately broken workflow:

```yaml
# .github/workflows/broken.yml
on: push
jobs:
  t:
    runs-on: ubuntu-latest
    steps:
      - run: echo ${{ github.event.pull_request.title }}
      - uses: actions/checkout@v3
    needs: build
```

```sh
$ actionlint
.github/workflows/broken.yml:3:3: job "t" needs job "build" which does not exist in this workflow [job-needs]
.github/workflows/broken.yml:6:23: "github.event.pull_request.title" is potentially untrusted. avoid using it directly in inline scripts. instead, pass it through an environment variable. [expression]
.github/workflows/broken.yml:7:15: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue [action]
$ echo $?
1
```

Three real bugs: a job that waits for one that doesn't exist, a script-injection hole (the _Pipeline
security_ lesson explains it), and an action too old to run. Messages are shortened here; actionlint adds a
link to the docs for each.

> **Figure.** A real terminal run of actionlint on the broken workflow. Three errors, each with the file, line and column, the message and a caret under the problem: job t needs job build which does not exist; github.event.pull_request.title is potentially untrusted in an inline script; actions/checkout@v3 is too old to run on GitHub Actions. The exit code is 1.
>
> The same run in a real terminal: each error points at the exact line and column, and the exit code 1 fails a pre-commit hook or CI job.

It checks structure, `needs:`, expressions, action inputs, outdated actions and, with shellcheck installed,
the shell in your `run:` steps. Run it in a pre-commit hook (the Git course's _Hooks_ lesson) and you'll
rarely see a broken workflow on GitHub.

## Mission: Give shop-api its first pipeline

Create the shop-api app, add a CI workflow with a lint job and a test job that runs only after lint passes, check it with actionlint, then push it on a branch and open a pull request to see both checks run.

- You need: Node.js 22+, a GitHub repository, actionlint
- You'll have: A pull request showing lint and test as passing checks

The whole app is two small files. `src/app.js`:

```js
import { createServer } from 'node:http'

export function priceWithTax(amount, rate = 0.18) {
  if (!Number.isFinite(amount) || amount < 0) throw new RangeError('amount must be a positive number')
  return Math.round(amount * (1 + rate) * 100) / 100
}

export function createApp() {
  return createServer((req, res) => {
    const url = new URL(req.url, 'http://localhost')
    if (url.pathname === '/health') return send(res, 200, { status: 'ok', version: process.env.APP_VERSION ?? 'dev' })
    if (url.pathname === '/price') {
      try {
        return send(res, 200, { total: priceWithTax(Number(url.searchParams.get('amount'))) })
      } catch (err) {
        return send(res, 400, { error: err.message })
      }
    }
    send(res, 404, { error: 'not found' })
  })
}

function send(res, status, body) {
  res.writeHead(status, { 'content-type': 'application/json' })
  res.end(JSON.stringify(body))
}
```

`src/server.js` starts it, and `test/app.test.js` tests it:

```js
// src/server.js
import { createApp } from './app.js'

const port = Number(process.env.PORT ?? 3000)
createApp().listen(port, () => console.log(`shop-api listening on :${port}`))
```

```js
// test/app.test.js
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { priceWithTax, createApp } from '../src/app.js'

test('adds 18% tax and rounds to cents', () => {
  assert.equal(priceWithTax(100), 118)
  assert.equal(priceWithTax(9.99), 11.79)
})

test('rejects a negative amount', () => {
  assert.throws(() => priceWithTax(-1), RangeError)
})

test('GET /health answers ok', async () => {
  const server = createApp().listen(0)
  const { port } = server.address()
  const res = await fetch(`http://localhost:${port}/health`)
  assert.equal(res.status, 200)
  assert.equal((await res.json()).status, 'ok')
  server.close()
})
```

```sh
$ mkdir -p shop-api/src shop-api/test shop-api/.github/workflows && cd shop-api && git init
$ npm init -y
$ npm pkg set type=module scripts.test="node --test" scripts.lint="node --check src/app.js && node --check src/server.js"
$ npm run lint && npm test           # after saving the three files above
$ nano .github/workflows/ci.yml      # the workflow from this lesson
$ actionlint && echo "workflow OK"
workflow OK
$ git add . && git commit -m "ci: add lint and test workflow"
$ gh repo create shop-api --private --source=. --push
$ git switch -c test/ci && git commit --allow-empty -m "test: trigger CI" && git push -u origin test/ci
$ gh pr create --fill && gh pr checks --watch
```

`node --check` checks one file per call, which is why the lint script runs it twice. `gh pr checks
--watch` shows **lint** finishing first and **test** starting after it, because of `needs: lint`. Break a
test on purpose, push again, and watch the pull request turn red. Later lessons add to this same
repository.

## Try it

- Add the CI workflow from this lesson to a repository and open a pull request to watch it run.
- Run the workflow by hand from the Actions tab using its Run workflow button.
- Install actionlint and run it in a repository with a workflow; then break `needs:` on purpose and run it again.
- Add `paths-ignore` for `'**.md'` and check that a README-only change no longer starts a run.
- Add a step that prints `${{ runner.os }}` and `${{ github.sha }}` and read them in the log.
- Write a schedule trigger for 03:30 IST and convert it to UTC.

## Quiz

1. Two jobs in one workflow have no needs between them. How do they run?
   - One after the other, in file order
   - **In parallel, each on its own fresh runner** (answer)
   - On the same machine, sharing files
   - Only the first one runs
   Why: Jobs are independent by default. needs makes one wait for another; files move between jobs only as artifacts or caches.

2. What happens to python-version: 3.10 in a workflow file?
   - Python 3.10 is installed
   - **YAML reads it as the number 3.1, so the wrong version is installed or the step fails** (answer)
   - actionlint rejects it
   - It is ignored
   Why: Unquoted 3.10 is a float. Quote versions: "3.10". actionlint doesn't flag this, so it's on you.

3. Which trigger lets you start a workflow by hand from the Actions tab?
   - push
   - **workflow_dispatch** (answer)
   - schedule
   - manual
   Why: workflow_dispatch adds a Run workflow button, and can take inputs. gh workflow run starts it from the terminal.

4. A schedule trigger says cron '0 9 * * *'. When does it run for a team in India?
   - 09:00 IST
   - **09:00 UTC, which is 14:30 IST** (answer)
   - Every 9 minutes
   - At 09:00 on the runner's local time
   Why: GitHub schedules use UTC. Runs can also start late at busy times, so never rely on the exact minute.

5. What is the difference between uses and run in a step?
   - None
   - **uses runs a reusable action, such as actions/checkout; run runs shell commands on the runner** (answer)
   - run is only for Windows
   - uses is deprecated
   Why: A step does one or the other. Actions take inputs under with; run steps can set env and shell.

## Resources

- [GitHub Docs: understanding GitHub Actions](https://docs.github.com/en/actions/get-started/understand-github-actions) (GitHub Docs)
- [GitHub Docs: workflow syntax](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax) (GitHub Docs)
- [GitHub Docs: events that trigger workflows](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows) (GitHub Docs)
- [GitHub-hosted runners: images and installed software](https://github.com/actions/runner-images) (GitHub)
- [actionlint: static checker for workflow files](https://github.com/rhysd/actionlint) (actionlint)
