Sub topic 3
Automating the build
This chapter assumes you can read simple YAML, use Git and the command line, and have built and tested a small application on your own machine. It covers what a build is, what makes an automated build trustworthy, and the errors that most often break one.
What a build is
A build turns source code into something that can run. The exact steps depend on the stack:
- A JavaScript project installs dependencies, then bundles and minifies the code into a
dist/folder. - A Java project resolves libraries, compiles classes, and packages a JAR file.
- A Go project compiles a single binary.
- A containerized service also assembles an image.
On a laptop, a build is often a loose sequence of commands that you remember. Build automation replaces that memory with a script or pipeline job that anyone, or any machine, can run and get the same result. Continuous integration depends on this. If the build needs a person to prepare the machine first, it can't run on every change.
Properties of a trustworthy automated build
An automated build is only useful if you can trust its result. Four properties matter most.
- One command. A single entry point, such as
npm run buildormake build, does everything. The pipeline calls the same command a developer calls locally. This keeps the logic in the repository instead of in CI tool settings, and you can debug a failed build without pushing commits to trigger it. - Clean starting state. The build starts from a fresh checkout on a fresh machine. Stale files from earlier runs, globally installed tools, and leftover environment variables are the usual cause of "it works on my machine."
- Pinned inputs. The same commit should produce the same output. That means pinning the language runtime version, the dependency versions, and the tool versions.
- Clear exit status. Every step reports success with exit code 0 and failure with a non-zero code. The pipeline stops at the first failure and marks the run as failed. A build that prints errors but exits 0 is worse than no build, because it reports success on broken code.
The working model: inputs, steps, outputs
Think of a build as a function. Its inputs are the source at a specific commit, the dependency versions, the toolchain version, and any build-time configuration. Its output is the build artifact. The pipeline can only trust the output if the inputs are fully known.
Each step is a point where the build can fail, and each failure should stop the run early. Failing early saves minutes and keeps the error message close to its cause.
Dependencies: the main source of drift
Most unreproducible builds come from dependencies. Two practices fix most of the problem.
Commit the lockfile. A manifest such as package.json says which version ranges are acceptable. A lockfile such as package-lock.json, poetry.lock, or go.sum records the exact versions that were resolved. Without it, a build run today and one run next week can pull different transitive dependencies from the same commit.
Use the install command that respects the lockfile. In npm, npm install may update the lockfile when it disagrees with the manifest. npm ci deletes node_modules, installs exactly what the lockfile lists, and fails if the lockfile and manifest are out of sync. In CI you want the failure, because it tells you a developer forgot to commit a lockfile change.
| Goal | Command in npm | Behavior |
|---|---|---|
| Add or update dependencies locally | `npm install` | May rewrite the lockfile |
| Reproducible install in CI | `npm ci` | Uses the lockfile only, fails on mismatch |
Other ecosystems have equivalents, such as pip install -r requirements.txt with pinned versions, or go build -mod=readonly.
A build script you can run anywhere
Keeping the build in a script means it runs the same way locally and in CI. This script cleans old output, installs from the lockfile, builds, and records which commit produced the output.
#!/usr/bin/env bash
set -euo pipefail
rm -rf dist
npm ci
npm run build
commit="$(git rev-parse HEAD)"
printf '{"commit":"%s","builtAt":"%s"}\n' \
"$commit" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > dist/build-info.json
echo "Build complete for ${commit}"The line set -euo pipefail makes the script stop on the first failing command (-e), treat unset variables as errors (-u), and fail a pipeline if any part of it fails (pipefail). Without it, Bash keeps going after an error, and the script can finish with exit code 0 even though a step broke.
The build-info.json file is a small piece of build metadata. When something misbehaves in production, you can read it to learn which commit is running.
Running the build in CI
The pipeline calls the same commands on a clean runner. This workflow uses the build script's steps directly and uploads the output.
name: build
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- name: Record build metadata
run: |
echo "{\"commit\":\"$GITHUB_SHA\"}" > dist/build-info.json
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/Three details are worth noting:
actions/checkout@v4gives the runner a fresh copy of the repository. Nothing from a previous run is present.node-version: 20pins the runtime. If you leave it out, the build uses whatever version the runner image ships with, and that can change when the image is updated.cache: npmstores the npm download cache between runs, keyed on the lockfile. It speeds up installs without changing whatnpm ciinstalls.
Running tests is a separate concern, covered in the next chapter. This chapter only requires that the build produce its output reliably.
Caching: faster builds without hidden state
Caching saves time by reusing work from earlier runs, such as downloaded packages or compiled objects. It also introduces risk, because a cache is state that survives between runs.
A good cache is keyed on its inputs. A dependency cache keyed on the hash of the lockfile is safe: when the lockfile changes, the key changes, and the old cache isn't used. A cache keyed on a fixed name like deps is unsafe, because it keeps serving old contents after dependencies change.
Cache the download directory rather than the installed node_modules folder when you can. npm ci removes node_modules anyway, and the download cache keeps the install deterministic.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| Passes locally, fails in CI | Different runtime version, or a file that exists only on your machine | Pin the runtime, then run the build in a clean checkout |
| `npm ci` fails with a lockfile mismatch | `package.json` changed without committing `package-lock.json` | Run `npm install` locally and commit the updated lockfile |
| Build passes, but output differs between runs | Unpinned dependencies, or timestamps and random values embedded in output | Pin versions, remove the nondeterministic inputs |
| Build is green, but the output is empty or broken | A step failed without a non-zero exit code | Use `set -euo pipefail` and check exit codes |
| Old code appears in new builds | Stale cache or leftover `dist/` folder | Key caches on the lockfile hash, clean the output folder first |
| Build fails only on some days | It downloads something at build time from an unpinned or unreliable source | Pin versions, and fetch dependencies through a registry mirror or cache |
Build configuration versus secrets
A build sometimes needs settings, such as an API base URL compiled into a frontend bundle. Keep two rules in mind.
First, avoid environment-specific builds. If you build one bundle for staging and another for production, you are no longer testing the thing you ship. Prefer to build once and supply environment settings when the artifact runs. The chapter on build artifacts returns to this idea.
Second, don't compile secrets into build output. Anything inside a bundle or image can be read by whoever receives it. The chapter on pipeline security covers secret handling.
Checklist for a build you can rely on
- The build runs from one command that works locally and in CI.
- The runtime and tool versions are pinned.
- The lockfile is committed, and CI installs with a lockfile-respecting command.
- The build starts from a clean checkout and cleans its output folder.
- Every step fails loudly with a non-zero exit code.
- Caches are keyed on their inputs, and the build still works with an empty cache.
- The output records the commit that produced it.
Exercise
A teammate's pull request passes the build on their laptop, but the CI build fails at the install step with an error that package.json and package-lock.json are not in sync. The pipeline uses npm ci. What most likely happened, and what should the teammate do?
Show answer
The teammate added or changed a dependency in package.json but did not commit the matching update to package-lock.json, or edited the lockfile in a way that no longer matches. npm ci refuses to install when the two disagree, which is the intended behavior because it catches the drift before it ships. The teammate should run npm install locally to regenerate the lockfile, commit package-lock.json together with package.json, and push again. They should not switch CI to npm install, because that would hide the problem and allow unpinned versions into the build.
Exercise
Your build caches node_modules under the fixed key deps. A week after a dependency upgrade, CI builds still contain the old version. Why does this happen, and how would you change the cache?
Show answer
A fixed key never changes, so the pipeline keeps restoring the old cached contents even though the lockfile now lists a newer version. Change the key to include a hash of the lockfile, so a lockfile change creates a new cache entry. Better, cache the package download directory instead of node_modules, since npm ci rebuilds node_modules from the lockfile.