27.6. Operating Repeated Administrative Jobs

Chapter 10 built the scheduling machinery - calendar expressions, timer and service pairs, cron's mail heritage. This section is about the job inside the schedule: how to write one that can be handed to any scheduler, kept from colliding with itself, watched when it fails, and rehearsed somewhere it cannot hurt anything. The design splits those concerns exactly along the boundaries of Figure 27.5:

Anatomy of a scheduled automation job

Figure 27.5. A timer activates a oneshot service running as john; the script owns correctness (lock, temporary work, atomic state); an OnFailure unit reports failure to the journal. A cron.d entry can drive the same script unchanged.

27.6.1. Separating Scheduling from Job Logic

The job itself is bin/run-job.sh - deliberately close to report.sh, because the reliability disciplines of Section 27.1 are the same at any scale:

#!/usr/bin/env bash
set -euo pipefail

base_dir=${1:-$HOME/debian-handbook/automation}
log_dir=$base_dir/logs
state_dir=$base_dir/state
mkdir -p "$log_dir" "$state_dir"

lock_file=$state_dir/run-job.lock
exec 9>"$lock_file"
flock -n 9 || {
  printf 'job already running\n' >&2
  exit 75
}

work=$(mktemp "$state_dir/.run.XXXXXX")
trap 'rm -f "$work"' EXIT

printf 'run at %s\n' "$(date -u +%FT%TZ)" > "$work"

if [[ -f $state_dir/fail ]]; then
  printf 'simulated failure: %s\n' "$(cat "$state_dir/fail")" >&2
  exit 1
fi

mv "$work" "$state_dir/last-run"
printf 'job completed at %s\n' "$(date -u +%FT%TZ)"

Everything the job knows is in the script: the lock, the staged work file, the atomic publish of state/last-run, a UTC timestamp (date -u +%FT%TZ), and a failure-injection hook - if state/fail exists, the job prints its contents as the reason and exits 1, which is what Section 27.6.2 uses to rehearse a failure. The base_dir argument exists so the script is testable against a scratch directory; the systemd unit runs it with no argument, on the real one. The unit is a file, /etc/systemd/system/automation-report.service:

[Unit]
Description=Automation report practice job
After=network-online.target
OnFailure=automation-report-alert.service

[Service]
Type=oneshot
User=john
Group=john
ExecStart=/home/john/debian-handbook/automation/bin/run-job.sh

and its schedule, /etc/systemd/system/automation-report.timer:

[Unit]
Description=Run the automation report practice job

[Timer]
OnCalendar=*-*-* 03:15:00
Persistent=true
RandomizedDelaySec=5m

[Install]
WantedBy=timers.target

The division of labor is strict: the unit owns identity (User=john, so the job writes nothing as root) and failure wiring (OnFailure=, used in Section 27.6.3); the timer owns when (03:15 nightly, plus up to five minutes of random delay so a fleet of machines does not stampede a shared service, plus Persistent=true so a machine that was off at 03:15 runs the job on next boot - the semantics Chapter 10 covered in Section 10.3.3); and the script owns what. Because the script is a plain executable, the scheduler is swappable - which the end of this section demonstrates by pointing cron at the very same file. Write both unit files, then load them:

$ sudo systemctl daemon-reload

daemon-reload is silent; it teaches systemd the two new units. Enable and start the timer:

$ sudo systemctl enable --now automation-report.timer
Created symlink '/etc/systemd/system/timers.target.wants/automation-report.timer' → '/etc/systemd/system/automation-report.timer'.

The symlink under timers.target.wants is what "enabled" means, and --now also started it. systemctl list-timers automation-report.timer --no-pager shows the next scheduled run - the same inspection Chapter 10 used in Section 10.3.4 - and the job's own output lands in the journal from the next run on.

The cron form of the same schedule is one file, provisioning/automation-report.cron:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15 3 * * * john /home/john/debian-handbook/automation/bin/run-job.sh >>/home/john/debian-handbook/automation/logs/cron.log 2>&1

The two SHELL=/PATH= lines matter more than they look: cron's default environment is minimal, and a job that works in your shell but not from cron is almost always an environment difference (Chapter 10, Section 10.4.2, covers cron's environment). The entry runs the identical script as john, at the identical time, appending both output streams to a log file - the file-logging alternative to systemd's journal. Install it as a system cron entry:

$ sudo install -m 0644 provisioning/automation-report.cron /etc/cron.d/automation-report
$ sudo cat /etc/cron.d/automation-report
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
15 3 * * * john /home/john/debian-handbook/automation/bin/run-job.sh >>/home/john/debian-handbook/automation/logs/cron.log 2>&1

The cat verifies what landed in /etc/cron.d - the same review habit as every configuration in this chapter. Which scheduler should a real job use? The systemd pair gives you the journal, OnFailure wiring, Persistent catch-up, and RandomizedDelaySec; cron gives you forty years of habit and mail-based failure notices. Pick one of the two in production - the lock from Section 27.6.2 makes an accidental double run harmless, but there is no reason to schedule the same job twice; this practice host now carries both, and Section 27.6.4 removes them together. Either way the architecture makes the choice low-stakes: the job does not know, and does not care.

27.6.2. Preventing Concurrent Runs and Handling Partial Work

A schedule is a promise about when, not a guarantee about durability - the previous run may still be busy when the next one fires, and a run that dies midway leaves the question of what it left behind. Both concerns are answered inside run-job.sh, and both can be watched through the unit. Start the job by hand the way the timer will:

$ sudo systemctl start automation-report.service

A oneshot service returns when its process exits; the start is silent. Read what the job published:

$ cat state/last-run
run at 2026-11-23T20:09:53Z

and the unit's own view of the run:

$ sudo systemctl status automation-report.service --no-pager
○ automation-report.service - Automation report practice job
     Loaded: loaded (/etc/systemd/system/automation-report.service; static)
     Active: inactive (dead) since Mon 2026-11-23 20:09:53 UTC; 3s ago
 Invocation: 3a8f528467da4d11b1b39382afc4bb6f
TriggeredBy: ● automation-report.timer
    Process: 62312 ExecStart=/home/john/debian-handbook/automation/bin/run-job.sh (code=exited, status=0/SUCCESS)
   Main PID: 62312 (code=exited, status=0/SUCCESS)
   Mem peak: 1.8M
        CPU: 21ms

Nov 23 20:09:53 auto1 systemd[1]: Starting automation-report.service - Automation report practice job...
Nov 23 20:09:53 auto1 run-job.sh[62312]: job completed at 2026-11-23T20:09:53Z
Nov 23 20:09:53 auto1 systemd[1]: automation-report.service: Deactivated successfully.
Nov 23 20:09:53 auto1 systemd[1]: Finished automation-report.service - Automation report practice job.

One reading note that saves an hour of confusion: this status command exits 3, because systemctl status uses its exit status to report unit state and a completed oneshot is inactive - the run itself says status=0/SUCCESS right in the Process line. Judge the job by that line, not by the command's exit status. The journal excerpt at the bottom is the run's whole life: started, one line of job output, finished. Concurrency protection is already inside - a second start while the script holds the lock exits 75 with job already running, and systemd does not start overlapping instances of the same oneshot unit anyway; the lock covers the cases systemd does not, like the cron entry above running the same script, or an administrator's manual run colliding with the timer.

Now rehearse a failure. Create the failure marker:

$ printf 'database connection refused\n' > state/fail

and start the job again:

$ sudo systemctl start automation-report.service
Job for automation-report.service failed because the control process exited with error code.
See "systemctl status automation-report.service" and "journalctl -xeu automation-report.service" for details.

The unit failed, and the status says so:

$ sudo systemctl status automation-report.service --no-pager
× automation-report.service - Automation report practice job
     Loaded: loaded (/etc/systemd/system/automation-report.service; static)
     Active: failed (Result: exit-code) since Mon 2026-11-23 20:10:01 UTC; 2s ago
 Invocation: 4fdf78901995473a82a150e7f2d8177f
TriggeredBy: ● automation-report.timer
    Process: 62417 ExecStart=/home/john/debian-handbook/automation/bin/run-job.sh (code=exited, status=1/FAILURE)
   Main PID: 62417 (code=exited, status=1/FAILURE)
   Mem peak: 1.8M
        CPU: 18ms

Nov 23 20:10:01 auto1 systemd[1]: Starting automation-report.service - Automation report practice job...
Nov 23 20:10:01 auto1 run-job.sh[62417]: simulated failure: database connection refused
Nov 23 20:10:01 auto1 systemd[1]: automation-report.service: Main process exited, code=exited, status=1/FAILURE
Nov 23 20:10:01 auto1 systemd[1]: automation-report.service: Failed with result 'exit-code'.
Nov 23 20:10:01 auto1 systemd[1]: Failed to start automation-report.service - Automation report practice job.
Nov 23 20:10:01 auto1 systemd[1]: automation-report.service: Triggering OnFailure= dependencies.

The interesting lines are the failure's evidence trail: the script's own diagnostic with the reason it read from the marker, and the last line - Triggering OnFailure= dependencies, the wiring Section 27.6.3 follows into the journal. Also check what the failure did not leave behind:

$ find state -maxdepth 1 -name '.run.*' -print

Nothing. The staged work file never became last-run: the script failed before the mv, and the EXIT trap removed the staging file - the atomic-publish discipline of Section 27.1.2 meaning that a failed run leaves the previous state in place and no debris beside it. state/last-run still holds the earlier, successful run's record. Recover, which is what an operator does at 3:20 a.m.:

$ rm -f state/fail
$ sudo systemctl start automation-report.service

The start is silent again. Confirm the recovery:

$ sudo systemctl status automation-report.service --no-pager
○ automation-report.service - Automation report practice job
     Loaded: loaded (/etc/systemd/system/automation-report.service; static)
     Active: inactive (dead) since Mon 2026-11-23 20:10:11 UTC; 1s ago
 Invocation: 5bcbe813f2434752baa38645c6cfc536
TriggeredBy: ● automation-report.timer
    Process: 62551 ExecStart=/home/john/debian-handbook/automation/bin/run-job.sh (code=exited, status=0/SUCCESS)
   Main PID: 62551 (code=exited, status=0/SUCCESS)
   Mem peak: 1.8M
        CPU: 20ms

Nov 23 20:10:11 auto1 systemd[1]: Starting automation-report.service - Automation report practice job...
Nov 23 20:10:11 auto1 run-job.sh[62551]: job completed at 2026-11-23T20:10:11Z
Nov 23 20:10:11 auto1 systemd[1]: automation-report.service: Deactivated successfully.
Nov 23 20:10:11 auto1 systemd[1]: Finished automation-report.service - Automation report practice job.

status=0/SUCCESS, and the state file is current again. One last inspection - whose files did all these runs leave?

$ sudo ls -l state/last-run
-rw------- 1 john john 28 Nov 23 20:10 /home/john/debian-handbook/automation/state/last-run

john's, mode 0600, because the unit runs as john. The lock file, the state file, the logs directory - all belong to the job's identity, not to root, and nothing the job ever writes requires a privileged cleanup. That is the User= line in the unit earning its keep, and the reason to give every scheduled job the least identity that can do its work (Chapter 10 built the same principle into its practice service, and Chapter 26 generalizes it).

27.6.3. Reporting Failures Through Logs and Notifications

A job that fails at 3:15 and tells no one fails twice. The alert unit the service references is small enough to read in full, /etc/systemd/system/automation-report-alert.service:

[Unit]
Description=Report a failed automation job

[Service]
Type=oneshot
ExecStart=/usr/bin/logger -t automation-report-alert "automation report job failed"

OnFailure= names it, so when the service failed in the previous subsection, systemd started this unit, whose one action is logger -t automation-report-alert … - a single syslog call with a tag. Find the notification the failure produced:

$ sudo journalctl -t automation-report-alert --no-pager -n 1
Nov 23 20:10:01 auto1 automation-report-alert[62425]: automation report job failed

The -t filter selects the tag logger wrote, and the line carries the exact timestamp of the failure from the previous subsection's journal - correlate it with the Triggering OnFailure= dependencies line there, and the alert has an audit trail, not just a message.

logger plus a tag is the floor of job reporting; build the ceiling out of the pieces this book has already covered:

  • Mail. cron's classic behavior is to mail a job's output to the owning user (Chapter 10, Section 10.4.2); a systemd path to the same end is an OnFailure unit whose ExecStart pipes the failed unit's journal into mail. Chapter 8 built the relay such mail needs (Section 8.7), so the alert lands in an inbox rather than a dead letter queue.
  • Aggregation. For anything more than a handful of hosts, route failures where the rest of the operations signal goes: Chapter 28 builds alert delivery with Prometheus Alertmanager (Section 28.7), whose silences, grouping, and "still failing" reminders solve the problem a raw journal line does not - a job that fails every night at 3:15 should nag differently on its first failure than on its thirtieth.

The design rule underneath all of them: the job's evidence lives in the journal (the service unit guarantees that - every run's stdout and stderr are captured), and the notification is a separate unit that reads that evidence. Keep the two separate and you can change how you are told without touching how the work is done.

27.6.4. Testing Automation in Disposable Environments

Every exercise in this chapter was structured so that its failure costs nothing: the shell scripts wrote into a workspace under john's home, etckeeper's /etc changes were demonstrated on practice files with a revert ready, Ansible failed against a single disposable host, the PXE services were confined to an isolated network, and this section's failure was injected by creating a marker file. That is the pattern to carry into production work, and it has three rules worth stating as rules:

First, rehearse the failure, not just the success. A scheduled job that has never been seen failing has never really been tested - the interesting behaviors (Does the alert fire? Is the partial work cleaned? Does the lock release?) only exist on the failure path, which is why Section 27.6.2 injected one deliberately and watched the whole response. When you build a job, build its failure mechanism at the same time - a marker file, a false condition, a scratch directory with no data - and use it before the schedule ever fires.

Second, test against a disposable environment that matches the real one's shape. The point of this chapter's two guests is not that they are virtual, but that they are structurally faithful: the same Debian release, the same sudo policy, the same network topology in miniature, management access kept separate from the experiments. Chapter 24 provides the machinery - snapshots for instant undo (Section 24.4.4), isolated networks (Section 24.3.3), clones for multi-host tests (Section 24.4.3). A test environment that differs from production in sudo policy, Python version, or network reachability teaches the wrong lessons precisely where automation is most sensitive.

Third, bound the cleanup to what the procedure created. Every practice unit in this section is removable in three commands. The timer first:

$ sudo systemctl disable --now automation-report.timer
Removed '/etc/systemd/system/timers.target.wants/automation-report.timer'.

Then the unit files and the cron entry - removals are silent:

$ sudo rm -f /etc/systemd/system/automation-report.service /etc/systemd/system/automation-report.timer /etc/systemd/system/automation-report-alert.service /etc/cron.d/automation-report
$ sudo systemctl daemon-reload

The rm also belongs in etckeeper's history - run sudo etckeeper commit 'Remove the practice job units' so the repository records the removal, closing the loop with Section 27.2. The /etc practice files from Section 27.2 (/etc/handbook-demo.conf and the secret file) can go the same way, each removal recorded. What remains after cleanup is the workspace with the scripts, state, and logs - the reader's own files, kept until they are not wanted.

The chapter's five subjects close into one loop here. A machine is provisioned unattended (27.4, 27.5), handed to configuration management (27.3), whose local /etc changes are tracked (27.2), while the recurring work that runs on all of them is scheduled, locked, logged, and rehearsed (27.1, this section). The common thread is not any particular tool - it is that every piece was written to be run again, verified against evidence, and recovered from when it failed. That is what "automation" actually means.