Idempotent Scripts Check the Current State Before Changing It

In progress

An operation is idempotent when running it once or ten times leaves the system in the same state. That property lets a playbook or terraform apply run on a schedule: a drifted server gets corrected, a correct one is left alone. Tools like Ansible build it in; a Bash script only gets it if every step checks before it acts.

Three Bash Techniques

Replace instead of appending. echo "x" >> file adds a duplicate line on every run. Edit the existing line in place:

sed -i 's/^#*HandleLidSwitch=.*/HandleLidSwitch=ignore/' /etc/systemd/logind.conf

Check before acting.

if ! grep -q "^overlay$" /etc/modules-load.d/k8s.conf; then
    echo "overlay" | tee -a /etc/modules-load.d/k8s.conf
fi

Fail fast, except where failure is expected. Start with set -euo pipefail, and mark the commands allowed to fail explicitly:

kubectl delete pod my-pod --ignore-not-found   # better than "|| true", which hides every error

What It Prevents

Configuration drift: servers changed by hand slowly diverge from what was intended. An idempotent definition re-applied regularly pulls them back without side effects from running twice.

References

Review cards

Flashcard Why prefer --ignore-not-found over || true in an idempotent script?

|| true also turns real failures (the API server down) into silent success. --ignore-not-found accepts only the expected case.

Flashcard Why does echo "x" >> file break idempotency, and what replaces it?

Each run appends another copy of the line. Edit the line in place with sed, or check with grep -q before appending.