Quick reference
The second run should leave the same state as the first.
- Name the state — One sentence: what this script owns, and what it must leave behind.
- Read, then write — install, ln -sfn, mkdir -p: each one a no-op on the second run.
- Guard the run — One lock, one run id, and a timeout on every call.
- Prove it twice — A second run in CI, and a diff that must be empty.
In one line: Twice is the test. The second run is where trust in a script is made.
Start this week:
- Run your last script twice in a test account.
- Replace one cp with install this week.
- Add a lock before the next scheduled run.
Explained
Same state, twice. Run it, record what matters, run it again, compare. The output can differ, with timestamps and IDs, but the state has to match.
Read before you write. install replaces a file and sets the mode, ln -sfn replaces a symlink without following it, mkdir -p tolerates the directory it made last time. Each is a no-op on the second run, which is the whole point.
Guard the run. A lock, a run id in every log line and a timeout on every call. Two copies of the same job are two writers, and the data bug they cause looks nothing like a scheduling problem.
Test the second run. In CI, against a disposable account: run, snapshot, run, diff, fail on any change. Then kill it halfway and run it again, because recovery is the path users meet.
Checklist
Run it before the first schedule and after every change to a write. A line that cannot be answered is the next test.
State
- The end state is written in one sentence.
- The script reads before it writes.
- Every write is a replace, not an append.
Guards
- One lock covers the whole run.
- Every network call has a timeout.
- A failed phase can be retried on its own.
Proof
- The second run is a CI test.
- The state diff is the assertion.
- A half-killed run recovers on the next start.
Operations
- Every run carries an id in its log lines.
- Exit codes separate retryable from failed.
- A dry run exists and is used before production.
The field guide
The full guide of the PDF (P1056), page by page.
Same input, same end state (definition)
Idempotent does not mean the output is identical. It means running it twice leaves the system in the same place as running it once.
The test is a pair of runs, not a code review. Run it, record the state, run it again, compare. A diff of zero is the only proof that survives a change of shell.
| Word | What it promises |
|---|---|
| Idempotent | A second run reaches the same state |
| Convergent | It gets there from any starting state |
| Repeatable | Same result, same machine |
| Resumable | It can continue after a stop |
- Name the state the script owns: files, rows, users, DNS records.
- Read the current state before deciding to write.
- Make every write a replace, not an append.
- Print what changed, so the second run can print nothing.
Append is the tell Every append-only script is idempotent until the day it runs twice, which is the day the queue retries.
If you cannot describe the end state in one sentence, the script cannot converge to it.
Check before you write (state)
Most unsafe re-runs come from a write that assumes a starting point. Reading first turns a create into an update and an update into a no-op.
Four safe primitives
mkdir -p /etc/acme
install -D -m 0644 app.conf /etc/acme/app.conf
ln -sfn /opt/acme/current/app /usr/local/bin/app
id -u deploy >/dev/null 2>&1 || useradd --system deployinstall replaces a file and sets the mode in one step. ln -sfn replaces a symlink without following it. mkdir -p tolerates the directory it made last time. Each one is a no-op on the second run.
| Instead of | Use |
|---|---|
| cp | install -m 0644 |
| ln -s | ln -sfn |
| mkdir | mkdir -p |
| useradd | id -u // useradd |
The delete that is missing A convergent script also removes what should not be there. rsync --delete and terraform apply both do, and both can surprise you the first time.
A write that cannot be repeated is a write that needs a human at 3 am.
One lock, one run, one log (the contract)
Concurrency is the failure mode people forget, because it looks like a data bug. Two runs of the same job are two writers.
Guard the run
set -euo pipefail
exec 9>/run/lock/deploy.lock
flock -n 9 || { echo "another run holds the lock" >&2; exit 75; }Exit 75 is EX_TEMPFAIL from sysexits.h: the run did not happen, and it is safe to try again. That is a different message from a failure, and the scheduler can treat it differently.
- Write a run id at the start and put it in every log line.
- Record the start and end of each phase, not just the total.
- Make a failed phase safe to retry on its own.
- Keep the last successful marker where the next run can read it.
Timeout is part of the contract A run with no timeout is a lock held forever. RuntimeMaxSec and systemd-run --on-active exist so a hung job does not become a hung queue.
Two runs that cannot see each other will eventually write over each other.
Test the second run (proof)
The second run is a test case, and it belongs in CI. If nobody runs it twice before production, production runs it twice for you.
- Run the script against a disposable account or container.
- Snapshot the state that matters: files, rows, cloud resources.
- Run it a second time with exactly the same input.
- Diff the snapshots, and fail the test on any change.
- Delete the environment, or the test becomes the incident.
The diff is the assertion
./provision.sh --env test
./provision.sh --env test
terraform plan -detailed-exitcode # 0 = converged, 2 = drift| Exit code | What it means |
|---|---|
| 0 | No changes, the script converged |
| 2 | Drift, the second run changed something |
| 1 | Error, read the plan |
Test the failure too Kill the script halfway and run it again. Recovery is the path your users will meet, not the clean run.
A script that has never been run twice has not been tested.
Reconcile, do not recreate (operations)
The mature version of idempotency is a reconciler: it reads the world, compares it with the desired state, and changes only the difference.
Terraform, Ansible, the Kubernetes controllers and systemd all work this way. The lesson for a hand-written script is the shape: plan, diff, apply, record.
| Tool | The idempotent verb |
|---|---|
| Terraform | plan, then apply |
| Ansible | playbook with --check --diff |
| kubectl | apply, after diff |
| systemd | enable --now, safe either way |
Read the plan, not the hope
terraform plan -detailed-exitcode
ansible-playbook site.yml --check --diff
kubectl diff -f deploy.yamlDestructive convergence A reconciler that deletes anything not in the desired state needs a guard rail: a protected list, a dry run, or a second pair of eyes.
Convergence is a property of the loop, not of the command.
The honest caveat: idempotency at the script level cannot save a non-idempotent API. A POST that creates an order will create two, however careful the shell is.
The lesson: the second run is the test, and the diff is the assertion.
Your turn: Which of your scripts has never been run twice?
Related on this site
More notes: Automation & tooling
- P1061Release automation commands
- P1060Five rules for credential automation
- P1059Observability as code
- P1058Scaffolding a new service from a template
- P1057Four numbers for automation
- P1055Cron to systemd timer: the migration path
- P1054Five signs your automation is fragile
- P1053Designing a CLI people keep using
Open in the notes app: search, filters, copy This note on GitHub