
Recall first from The brief, requirements and architecture
- A suite is one library plus thin tools: logging, config, locking and dry-run live in lib/, not copied per script.
- Scope an MVP first: five working tools with tests beat ten half-finished ones.
- --dry-run rehearses the exact commands; --force allows destructive steps, never skips the checks.
Provision: bootstrap a fresh board
3 min readThe architecture fixed one library, one config format, one log format and one exit-code convention. This lesson answers: how do provision, backup and monitor turn that into the suite's three core tools?
Provision runs on the board, over SSH, as the sudo-capable user you set up in S03B. It applies the fleet policy in a fixed order, and every step is idempotent.
Parse: flags and config load; dry-run mode is decided before any work.
Lock: take_lock provision stops two runs from racing on one board.
Packages: apt-get update and install reach the required package set.
Account and key: the ops user exists and holds the fleet public key.
Hardening: the sshd drop-in is rendered from a template and installed; sudo rules follow the same pattern.
Verify: sshd -t passes, the policy is dumped, and the run reports.
1Packages and the automation account
apt-get install -y is already idempotent: installed packages are left alone. Guard account creation with a state check:
run sudo apt-get update
run sudo apt-get install -y rsync unattended-upgrades
if ! id -u ops >/dev/null 2>&1; then
run sudo useradd -m -s /bin/bash ops
fi
run sudo groupadd -f sshusers
run sudo usermod -aG sshusers ops
groupadd -f succeeds quietly when the group exists. The ops account is a key-only automation account; it gets tightly scoped sudo rules from S11A, not full root.
2Install the fleet key without duplicating it
The suite ships a public key at etc/opskit.pub. Install it for ops with the check-before-append pattern:
pub=$(cat "$OPSKIT_KEY_PUB")
run sudo install -d -m 0700 -o ops -g ops /home/ops/.ssh
if ! sudo grep -qF "$pub" /home/ops/.ssh/authorized_keys 2>/dev/null; then
printf '%s\n' "$pub" | run sudo tee -a /home/ops/.ssh/authorized_keys >/dev/null
run sudo chown ops:ops /home/ops/.ssh/authorized_keys
run sudo chmod 0600 /home/ops/.ssh/authorized_keys
fi
grep -qF searches for the key as a fixed string, quietly. A second run finds it and appends nothing. install -d creates the directory with the right owner and mode in one step.
3Render hardening from a template
A template is a file with holes that config fills. A heredoc is the simplest template engine: unquoted EOF expands variables, quoted 'EOF' stays literal. Render to a temp file, compare, and install only when the content actually changed:
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
cat > "$tmp" <<EOF
# Managed by OpsKit provision. Do not edit by hand.
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowGroups sshusers
EOF
if ! sudo cmp -s "$tmp" /etc/ssh/sshd_config.d/10-opskit.conf; then
run sudo install -D -m 0644 "$tmp" /etc/ssh/sshd_config.d/10-opskit.conf
run sudo sshd -t
run sudo systemctl reload ssh
fi
cmp -s compares silently. Skipping identical rewrites saves flash writes and avoids needless service reloads. install -D creates leading directories. sshd -t validates before the reload; under set -e a failed validation stops the script before the reload runs. The drop-in works because Ubuntu's sshd_config includes sshd_config.d/*.conf first and the first obtained value wins, as S11A explained.
PasswordAuthentication no takes effect the moment sshd reloads. Prove a key login for ops from a second terminal first, and keep your current session open until the new one works. Make sure learner is also in sshusers, or AllowGroups locks out the admin too. On a headless board the rescue path is the serial console from S03B. Keep the previous drop-in file so a bad render can be restored.
Backup: snapshots you can restore
3 min readThe backup tool is the S10A snapshot recipe, wrapped in the suite's library. Each run names a snapshot by date, links unchanged files against the newest previous snapshot, and copies only what changed. --link-dest needs the reference on the same filesystem as the destination, because hard links cannot cross filesystems.
1Take the snapshot
src=/home/ops/data/
root=/srv/backups/data
today=$(date +%F)
mkdir -p "$root"
prev=$(find "$root" -mindepth 1 -maxdepth 1 -type d -name '20*' \
! -name "$today" | sort | tail -n 1)
args=(-a --delete)
[ -n "$prev" ] && args+=(--link-dest="$prev")
if run rsync "${args[@]}" "$src" "$root/$today/"; then
log INFO "snapshot $today complete"
else
rc=$?
if [ "$rc" -eq 24 ]; then
log WARN "source files vanished mid-run; snapshot may be partial"
else
die "rsync failed with status $rc"
fi
fi
The trailing slash on src/ copies the contents, not the directory itself. Date-named directories sort chronologically, so tail -n 1 finds the newest reference. rsync exit 24 means files vanished during the run, a warning on a live system; exit 23 means some files failed to transfer, and treating it as success would lie to you.
2Rotate with a retention policy
Keep the newest OPSKIT_KEEP snapshots. Pruning is destructive, so it requires --force; without it the tool only reports what it would prune:
find "$root" -mindepth 1 -maxdepth 1 -type d -name '20*' | sort |
head -n -"$OPSKIT_KEEP" |
while IFS= read -r old; do
if [ "${FORCE:-0}" = 1 ]; then
run rm -rf -- "$old"
else
log INFO "would prune $old (use --force to prune)"
fi
done
head -n -7 prints all lines except the last seven, so only the oldest reach rm. Test the pipeline with echo in place of rm -rf -- before trusting it; an off-by-one here deletes a snapshot you meant to keep. Deleting a snapshot is safe for the others: removing a hard link only decrements the inode's link count.
3Prove a restore
A backup you have never restored is a guess. Copy a snapshot out and compare:
cp -a /srv/backups/data/2026-11-16/ /home/ops/data-restored/
diff -r /home/ops/data /home/ops/data-restored
cp -a copies data into new files, so the test cannot disturb the snapshots. Run this right after the first snapshot and after every change to the tool, and schedule a periodic restore test as its own job. The demo requires exactly this proof.
Snapshots share inodes. Editing a file in place inside one snapshot changes every snapshot that links it. Never edit or run repair tools inside the snapshot tree; restore by copying out. And rehearse any --delete run with --dry-run first: a wrong or empty source empties the destination to match.
Monitor: health checks with thresholds
3 min readMonitor is read-only. It reads identity (hostname, kernel, uptime), then runs one check per subsystem. A A threshold is a configured limit; a metric past it turns a check from PASS to FAIL. comes from config, never from a magic number buried in code. Each check prints one line to standard output and returns a status:
check_disk() {
local used
used=$(df -P / | awk 'NR==2 {sub(/%/,"",$5); print $5}')
if [ "$used" -ge "$OPSKIT_DISK_LIMIT" ]; then
printf 'FAIL disk %s%% >= %s%%\n' "$used" "$OPSKIT_DISK_LIMIT"
return 1
fi
printf 'PASS disk %s%%\n' "$used"
}
check_load() {
local cores
cores=$(nproc)
if awk -v c="$cores" '{exit !($1 > c)}' /proc/loadavg; then
printf 'FAIL load %s over %s cores\n' "$(cut -d' ' -f1 /proc/loadavg)" "$cores"
return 1
fi
printf 'PASS load %s\n' "$(cut -d' ' -f1 /proc/loadavg)"
}
check_services() {
local svc failed=0
if ! command -v systemctl >/dev/null 2>&1; then
printf 'SKIP services no systemd\n'
return 0
fi
read -r -a services <<< "$OPSKIT_SERVICES"
for svc in "${services[@]}"; do
if systemctl is-active --quiet "$svc"; then
printf 'PASS service %s\n' "$svc"
else
printf 'FAIL service %s inactive\n' "$svc"
failed=1
fi
done
return "$failed"
}
check_temp() {
local zone=/sys/class/thermal/thermal_zone0/temp
if [ ! -r "$zone" ]; then
printf 'SKIP temp no thermal zone\n'
return 0
fi
local c=$(( $(cat "$zone") / 1000 ))
if [ "$c" -ge "$OPSKIT_TEMP_LIMIT" ]; then
printf 'FAIL temp %sC >= %sC\n' "$c" "$OPSKIT_TEMP_LIMIT"
return 1
fi
printf 'PASS temp %sC\n' "$c"
}
df -P gives the portable one-line-per-filesystem format, and awk strips the percent sign. The load check compares the one-minute average against the core count: load above core count means tasks are waiting for CPU. read -r -a splits the configured service list into an array safely, with no unquoted expansion. The temperature check reads millidegrees and divides by 1000. Checks that do not apply to a host report SKIP, not FAIL: a minimal container has no thermal zone and no systemd, so one suite serves both host types.
The main function runs every check and counts failures:
fails=0
for check in check_disk check_load check_services check_temp; do
"$check" || fails=$((fails + 1))
done
[ "$fails" -eq 0 ] || exit 1
One FAIL anywhere exits 1, and the report lines say exactly which check failed. A memory check reading MemAvailable from /proc/meminfo follows the same shape; add it as your first stretch card. Real monitoring systems inherit a richer convention from Nagios plugins: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. OpsKit's MVP keeps two states; warning bands are a stretch goal.
Going deeperWhat load average really counts on Linux
The three numbers in /proc/loadavg are exponentially damped averages over one, five and fifteen minutes. Linux counts tasks that are runnable plus tasks in uninterruptible sleep, the D state, usually waiting on disk I/O. Traditional Unix counted only runnable tasks. The difference matters on a board: a Pi stuck on slow SD-card I/O shows a high load average while the CPU sits mostly idle. That is why the monitor reads load alongside disk usage and temperature instead of trusting one number. Compare against nproc, and read the fifteen-minute field to tell a sustained problem from a brief spike.
/sys/class/thermal/thermal_zone0/temp reports millidegrees Celsius; 47234 means 47.2 degrees. On Raspberry Pi OS, vcgencmd measure_temp prints the same reading in friendlier form. The firmware lowers CPU frequency when the SoC gets too hot, so a throttled board looks slow before it looks hot. Read trip_point_0_temp in the same directory for the critical trip point on your board. Sustained readings near your limit mean cooling or workload problems, not a bigger threshold.
Key takeaways
- Every tool is idempotent: check state before changing it, so re-runs and catch-up runs are safe.
- Backups are --link-dest snapshots plus a proven restore; a backup you never restored is a guess.
- Each health check reads a metric, compares it to a configured threshold and prints one PASS, FAIL or SKIP line; checks that do not apply report SKIP, not FAIL.
- Snapshots are immutable: editing a file inside one changes every snapshot sharing it, so restore by copying out and never repair in place.
Reflect
- Explain to a colleague, in two sentences: implement idempotent provision, backup, monitor, update and security tools that are safe to re-run.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
Official documentation first. Links checked when the lesson was published.