Sub topic 7
Using actions and running shell commands
This chapter assumes you can read YAML, know what a workflow file and a job are, and have run a build tool such as npm from a shell. Each step in a job does one of two things. It either runs a shell command with run, or it calls a reusable action with uses.
Two kinds of step
A run step passes its text to a shell on the runner. A uses step runs a packaged action, which is a unit of code someone else wrote and versioned. You can mix both in the same job.
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm testThe first step, actions/checkout@v4, copies your repository onto the runner. A runner starts with an empty workspace, so without this step npm ci has no package.json to read. The second step installs Node 20. The last two steps are plain shell commands.
Anatomy of a uses step
The value of uses has the form owner/repo@ref. The ref after the @ is a tag, a branch, or a commit SHA, and it decides which version of the action runs.
with:passes inputs to the action. Each key must match an input the action declares.env:sets environment variables for that step.id:names the step so later steps can read its outputs.
A uses step cannot also have a run key. Each step does one or the other.
Anatomy of a run step
By default, run uses bash on Linux and macOS and pwsh on Windows. Set shell: to change that. Use | for a multi-line script.
steps:
- name: Build and report
shell: bash
working-directory: ./app
run: |
npm ci
npm run build
echo "Build finished in $(pwd)"On Linux, GitHub's default bash invocation runs with -e. A multi-line script stops at the first command that fails, and the step fails with it. If you set shell: bash explicitly, GitHub adds -eo pipefail, so a failure in the middle of a pipe also fails the step.
Choosing a version for uses
| Reference | Example | Trade-off |
|---|---|---|
| Major tag | `actions/checkout@v4` | Receives fixes automatically, but the tag can move. |
| Full tag | `actions/[email protected]` | More predictable, but still a movable tag. |
| Commit SHA | `actions/checkout@<40-character-sha>` | Immutable, which is the safest choice for third-party actions. |
Common errors
- Forgetting
actions/checkout, which leaves the workspace empty. - Putting
with:on arunstep. Onlyusessteps accept inputs. - Passing an input name the action does not declare. The input is ignored and you get a warning.
- Assuming
cdin onerunstep carries over to the next. Each step starts in a fresh shell, so useworking-directoryinstead.
Exercise
A step contains both uses: actions/setup-node@v4 and run: npm test. Why does the workflow fail to load, and how do you fix it?
Show answer
A step can have either uses or run, not both. Split it into two steps: one that uses actions/setup-node@v4 (with with: for its inputs) and one that runs npm test.