By the end you'll know
- How to see which updates a server is waiting for, and which are security fixes
- Why "the server updates itself" is worth checking, not assuming
- How to patch with a script that restarts the app and checks it still works
- When a server needs a reboot, and how to tell for sure
- How to get an alert the moment a patch run fails, and how to undo a patch
Before you start
- You need: Vagrant and VMware Fusion or VirtualBox, as set up in Linux Lesson 7, and a free account at Healthchecks.io (opens in a new tab).
- The practice folder:
git clone https://github.com/Kwamib/automation-practice.git, orgit pullin it if you have it from Lesson 1. - This lesson uses
aptfrom Linux Lesson 8, services andjournalctlfrom Linux Lesson 7, and timers from Linux Lesson 13. - Where commands run: on your own computer to build the server, then on the server, called
web-1. - The output below is from real runs on November 18, 2026, from about 9:30am in New York (14:30 UTC).
Why patching matters
A patch is an update that fixes a problem in software that's already installed. Many of them fix security holes. Once a fix is published, attackers know exactly where the hole is, and look for servers that haven't installed the fix yet.
The famous example is Equifax. In March 2017, a fix came out for a serious hole in Apache Struts, software Equifax used on a public website. Equifax didn't install it. Attackers got in through that hole in May, and took the personal details of about 147 million people.
So why doesn't everyone patch straight away? Because patching can break things. An update restarts a service, changes a library, or needs a reboot, and the app goes down. Teams that have been burned by that start putting patching off.
The answer is to patch regularly, in a way that finds any breakage right away, tells you, and can be undone. That's what this lesson builds.
The server
On your own computer:
cd ~/Apps/automation-practice
vagrant up
vagrant snapshot save before-patch
vagrant ssh
vagrant up: builds the server from theVagrantfileand runsserver/setup.shon it. That installs nginx, a web server, showing a one-line bookshop page, plus the patch script, its service and its timer.vagrant snapshot save before-patch: saves a copy of the whole server, namedbefore-patch. It's your undo button, and you'll use it at the end.vagrant ssh: logs you in to the server.
The server is made from a ready-made image (a box) that's about a month old, so real updates are waiting.
What's waiting
(On the server)
uname -r
apt list --upgradable 2>/dev/null | grep -c 'upgradable from'
apt list --upgradable 2>/dev/null | grep -c -- '-security'
6.8.0-86-generic
245
173
uname -r: the version of the Linux kernel that's running.-rmeans "release". The kernel is the core of the operating system.apt list --upgradable: lists every installed package that has a newer version waiting.2>/dev/nullhides a warningaptprints:2is the error output, and/dev/nullthrows it away.| grep -c 'upgradable from':|passes the list togrep, which searches it.-ccounts the matching lines instead of printing them. Each pending update has one.grep -c -- '-security': counts updates from Ubuntu's security channel.--means "no more options", so-securityis read as text to find, not as a flag.
245 updates waiting, 173 of them security fixes, on a server that's only a month out of date.
Doesn't Ubuntu update itself?
Normally, yes: Ubuntu includes unattended-upgrades, which installs security fixes once a day on its own. So check it's actually there:
cat /etc/apt/apt.conf.d/20auto-upgrades
systemctl list-timers 'apt-daily*' --no-pager
dpkg -l unattended-upgrades 2>/dev/null | tail -1
cat: /etc/apt/apt.conf.d/20auto-upgrades: No such file or directory
NEXT LEFT LAST PASSED UNIT ACTIVATES
0 timers listed.
un unattended-upgrades <none> <none> (no description available)
cat FILE: prints a file.20auto-upgradesis the file that turns automatic updates on.systemctl list-timers 'apt-daily*': the timers that run automatic updates, if any.*means "anything after".--no-pagerprints it all at once.dpkg -l unattended-upgrades: shows whether a package is installed.-lmeans "list".tail -1keeps only the last line.
None of it is there. The file is missing, there are no timers, and un means the package isn't installed (u for "nobody asked for it", n for "not installed"). The company that makes this box removes automatic updates from it. Many images and cloud templates are set up differently from a normal install. Never assume a server patches itself; check.
On a normal Ubuntu server, you'd turn it on with sudo apt install unattended-upgrades, then sudo dpkg-reconfigure -plow unattended-upgrades (-plow asks only the basic questions). This lesson doesn't, because even when it's on, automatic updates leave three gaps:
- They don't restart your app or check it still works.
- They don't reboot, unless you turn that on, so a new kernel sits installed but unused.
- They don't tell anyone if they fail.
The patch script fills those gaps.
Holding a package back
Sometimes you know an update would break something, or you want to test it first. You can tell apt to leave one package alone:
sudo apt-mark hold nginx
nginx set on hold.
sudo: run as root, the administrator.apt-mark hold nginx: never update nginx until you say so.sudo apt-mark unhold nginxundoes it, andapt-mark showholdlists everything held.
Holds are easy to forget, and a forgotten hold means a package that never gets its security fixes. The patch script lists every hold on every run, so they stay visible.
The patch script
server/patch-server, installed at /usr/local/bin/patch-server. You can read the whole file on GitHub (opens in a new tab). It has three modes:
| Command | What it does |
|---|---|
sudo patch-server | A dry run: lists every update it would install, and changes nothing |
sudo patch-server --apply | Installs the updates, restarts the app, and checks the app still works |
sudo patch-server --check | Only checks the app still works |
And it ends with an exit code: 0 if everything worked and the app is healthy, 1 if an update failed or the app is down afterwards, 2 if it was run wrongly.
The whole script:
#!/usr/bin/env bash
# patch-server: install pending updates, restart the app, and check it still works.
#
# patch-server show what would be updated, and change nothing
# patch-server --apply update, restart the app, then check it
# patch-server --check only check the app
#
# Exit codes: 0 done and the app is healthy, 1 an update failed or the app is
# down afterwards, 2 called wrongly.
set -euo pipefail
APP_SERVICE=${APP_SERVICE:-nginx}
HEALTH_URL=${HEALTH_URL:-http://127.0.0.1/}
HEALTH_TEXT=${HEALTH_TEXT:-bookshop is up}
LOCK=${LOCK:-/run/lock/patch-server.lock}
LOG_DIR=${LOG_DIR:-/var/log/patch-server}
log() { printf '%s patch-server: %s\n' "$(date -u +%FT%TZ)" "$*" >&2; }
usage() { echo "usage: patch-server [--apply | --check]" >&2; exit 2; }
mode=dry
case "${1:-}" in
"") ;;
--apply) mode=apply ;;
--check) mode=check ;;
*) usage ;;
esac
[ $# -le 1 ] || usage
[ "$(id -u)" -eq 0 ] || { log "run me as root (sudo): installing updates needs it"; exit 2; }
# One run at a time.
exec 9>"$LOCK"
if ! flock -n 9; then
log "another run is still going; skipping this one"
exit 0
fi
# Is the app answering, with the page it should? Five tries, two seconds apart,
# because a service that's just been restarted can take a moment.
health() {
local try
for try in 1 2 3 4 5; do
if curl -fsS --max-time 5 "$HEALTH_URL" 2>/dev/null | grep -qF "$HEALTH_TEXT"; then
log "health check passed: $HEALTH_URL answers '$HEALTH_TEXT'"
return 0
fi
sleep 2
done
log "health check FAILED: $HEALTH_URL didn't answer '$HEALTH_TEXT' after 5 tries"
return 1
}
if [ "$mode" = check ]; then
health && exit 0 || exit 1
fi
# apt, with no questions asked: wait up to 5 minutes if another apt (like the
# automatic updates) is running, keep our own config files when a package ships
# a new one, and let needrestart restart services without asking.
apt_opts=(-o DPkg::Lock::Timeout=300 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
log "refreshing the package lists"
apt-get "${apt_opts[@]}" -qq update
# One line per pending update: "name/suites version arch [upgradable from: old]".
mapfile -t pending < <(apt list --upgradable 2>/dev/null | grep -F '[upgradable from:' || true)
mapfile -t held < <(apt-mark showhold)
security=0
for p in "${pending[@]}"; do
case "$p" in *-security*) security=$((security + 1)) ;; esac
done
log "${#pending[@]} updates pending, $security of them security fixes"
[ "${#held[@]}" -eq 0 ] || log "held back on purpose: ${held[*]}"
if [ "$mode" = dry ]; then
for p in "${pending[@]}"; do
name=${p%%/*}
read -r _ new _ <<<"$p"
old=${p##*from: }; old=${old%]}
note=""
for h in "${held[@]}"; do [ "$h" = "$name" ] && note=" (held: won't be updated)"; done
log "would update $name $old -> $new$note"
done
log "dry run: nothing was changed. Add --apply to update."
exit 0
fi
mkdir -p "$LOG_DIR"
apt_log="$LOG_DIR/$(date -u +%Y%m%dT%H%M%SZ).log"
status=0
if [ "${#pending[@]}" -eq 0 ]; then
log "nothing to update"
else
log "updating; apt's full output goes to $apt_log"
if apt-get "${apt_opts[@]}" -y --with-new-pkgs upgrade >"$apt_log" 2>&1; then
log "updated $(grep -c '^Setting up' "$apt_log" || true) packages"
else
log "the update FAILED; see $apt_log"
status=1
fi
fi
# Restart the app even if nothing in it changed: if an update (or anything
# else) has broken it, find out now, in the maintenance window, not at the
# next reboot.
log "restarting $APP_SERVICE, so a problem shows now and not at the next reboot"
systemctl restart "$APP_SERVICE" || log "$APP_SERVICE didn't restart; see: journalctl -u $APP_SERVICE"
health || status=1
if [ -f /run/reboot-required ]; then
log "a reboot is needed to finish, for: $(sort -u /run/reboot-required.pkgs 2>/dev/null | tr '\n' ' ')"
fi
exit "$status"
The important parts, in order:
One run at a time. Like Lesson 1 of the Linux track's scripts and this track's backup job, it takes a lock first, so two patch runs can never overlap:
exec 9>"$LOCK"
if ! flock -n 9; then
log "another run is still going; skipping this one"
exit 0
fi
exec 9>"$LOCK": opens the lock file as file number 9, for as long as the script runs.flock -n 9: takes the lock on it.-nmeans "don't wait": if another run has it, give up at once.
apt, with no questions. A script can't answer questions, so apt is told not to ask any:
apt_opts=(-o DPkg::Lock::Timeout=300 -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
DPkg::Lock::Timeout=300: if anotheraptis running, such as automatic updates, wait up to 300 seconds (5 minutes) for it instead of failing at once.--force-confdefand--force-confold: when an update brings a new version of a config file you've changed, keep yours. Without these,aptstops and asks.DEBIAN_FRONTEND=noninteractive: never show a question on screen.NEEDRESTART_MODE=a: Ubuntu'sneedrestarttool restarts services that use updated libraries;ameans "automatically, without asking".
Refresh, count, and list.
apt-get "${apt_opts[@]}" -qq update
mapfile -t pending < <(apt list --upgradable 2>/dev/null | grep -F '[upgradable from:' || true)
mapfile -t held < <(apt-mark showhold)
apt-get update: downloads the latest list of available versions. It doesn't install anything.-qqmeans "very quiet".mapfile -t pending: reads each line into a list calledpending, one update per line.-tdrops the line endings.< <(...)feeds it the output of the command inside.grep -F: matches the text exactly (-Fmeans "fixed text", so[isn't treated as special).
Install, keeping the full output.
apt-get "${apt_opts[@]}" -y --with-new-pkgs upgrade >"$apt_log" 2>&1
upgrade: install the newer versions. Held packages are skipped.-y: answer "yes" to "Do you want to continue?".--with-new-pkgs: allow new packages when an update needs them. A new kernel arrives as new packages, so without this it would be held back.>"$apt_log" 2>&1: send everythingaptprints into a log file in/var/log/patch-server/. The job's own log stays short, and the full detail is there if something fails.
Restart the app, then check it.
systemctl restart "$APP_SERVICE" || log "$APP_SERVICE didn't restart; see: journalctl -u $APP_SERVICE"
health || status=1
This is the most important idea in the lesson. The script restarts the app every time, even when nothing in the app was updated. If anything has broken it, from an update or from something else, the problem shows now, during the patch run, while someone's watching for it. Not at the next reboot, weeks later, at a bad time.
The health check fetches the bookshop's page and looks for the words "bookshop is up". It tries 5 times, 2 seconds apart, because a service that's just restarted can take a moment:
curl -fsS --max-time 5 "$HEALTH_URL" 2>/dev/null | grep -qF "$HEALTH_TEXT"
curl: fetches a web page.-ffails on an error page,-sSstays quiet unless something goes wrong, and--max-time 5gives up after 5 seconds.grep -qF: looks for the exact text (-F) and prints nothing (-q); it only reports found or not found.
Checking the page says the right thing is better than checking the server answers at all. A web server can answer with an error page, and that still counts as "up" to a lazy check.
Does it need a reboot? The last part compares the newest kernel installed in /boot with the one running (uname -r). If they differ, a reboot is needed to finish. More on that below.
The service and the timer
server/patch-server.service runs the script; server/patch-server.timer decides when:
[Service]
Type=oneshot
Environment=HC_URL_FILE=/etc/patch-server/ping-url
ExecStart=/usr/local/bin/patch-server --apply
ExecStopPost=/usr/local/bin/hc-ping
TimeoutStartSec=30min
[Timer]
OnCalendar=Sun *-*-* 03:00:00 UTC
RandomizedDelaySec=15min
Persistent=true
Type=oneshot: runs, finishes, done, like a script.- It runs as root, because only root can install updates. That's why the script is kept short and simple: everything in it runs with full power.
ExecStopPost=/usr/local/bin/hc-ping: after every run, however it ended, report the result to Healthchecks.io. More on that below.TimeoutStartSec=30min: a run still going after 30 minutes is stopped, and counts as a failure.OnCalendar=Sun *-*-* 03:00:00 UTC: every Sunday at 03:00 UTC. That's the maintenance window: a regular time when a short outage hurts least, and everyone knows patching happens.RandomizedDelaySec=15min: start at a random moment up to 15 minutes later. With 50 servers on the same timer, they don't all patch, and restart, at once.Persistent=true: if the server was off on Sunday at 3am, run as soon as it's back.
A dry run first
sudo patch-server
2026-11-18T14:31:40Z patch-server: refreshing the package lists
2026-11-18T14:31:41Z patch-server: 245 updates pending, 173 of them security fixes
2026-11-18T14:31:41Z patch-server: held back on purpose: nginx
2026-11-18T14:31:41Z patch-server: would update apparmor 4.0.1really4.0.1-0ubuntu0.24.04.4 -> 4.0.1really4.0.1-0ubuntu0.24.04.9
...
2026-11-18T14:31:41Z patch-server: would update curl 8.5.0-2ubuntu10.6 -> 8.5.0-2ubuntu10.16
...
2026-11-18T14:31:41Z patch-server: would update linux-image-generic 6.8.0-86.87 -> 6.8.0-149.149
...
2026-11-18T14:31:41Z patch-server: would update openssh-server 1:9.6p1-3ubuntu13.14 -> 1:9.6p1-3ubuntu13.20
2026-11-18T14:31:41Z patch-server: would update openssl 3.0.13-0ubuntu3.6 -> 3.0.13-0ubuntu3.16
...
2026-11-18T14:31:41Z patch-server: would update sudo 1.9.15p5-3ubuntu5.24.04.1 -> 1.9.15p5-3ubuntu5.24.04.4
2026-11-18T14:31:41Z patch-server: would update systemd 255.4-1ubuntu8.11 -> 255.4-1ubuntu8.18
...
2026-11-18T14:31:41Z patch-server: dry run: nothing was changed. Add --apply to update.
All 245, with the old version and the new one. A few worth noticing: openssh-server, which lets people log in remotely; openssl, which handles encryption; sudo; and linux-image-generic, the kernel, jumping from 86 to 149. These are exactly the packages attackers look for out-of-date versions of.
Patch it
Run the job the way the timer will, through its service:
sudo systemctl start patch-server.service
Warning! D-Bus connection terminated.
Failed to wait for response: Connection reset by peer
That looks like a failure, and it isn't. One of the 245 updates is systemd itself. When systemd is updated, it restarts itself in place, and that cuts off systemctl, which was waiting for the job to finish. The job carries on. Follow its log to see:
journalctl -u patch-server.service -f -o short-iso
-u patch-server.service: only this service's log.-f: "follow": keep showing new lines as they arrive. Press Ctrl+C to stop following; it doesn't stop the job.-o short-iso: dates like2026-11-18T14:33:21.
2026-11-18T14:31:51+00:00 web-1 patch-server[3727]: 2026-11-18T14:31:51Z patch-server: refreshing the package lists
2026-11-18T14:31:52+00:00 web-1 patch-server[3727]: 2026-11-18T14:31:52Z patch-server: 245 updates pending, 173 of them security fixes
2026-11-18T14:31:52+00:00 web-1 patch-server[3727]: 2026-11-18T14:31:52Z patch-server: held back on purpose: nginx
2026-11-18T14:31:52+00:00 web-1 patch-server[3727]: 2026-11-18T14:31:52Z patch-server: updating; apt's full output goes to /var/log/patch-server/20261118T143152Z.log
...
2026-11-18T14:33:21+00:00 web-1 patch-server[3727]: 2026-11-18T14:33:21Z patch-server: updated 272 packages
2026-11-18T14:33:21+00:00 web-1 patch-server[3727]: 2026-11-18T14:33:21Z patch-server: restarting nginx, so a problem shows now and not at the next reboot
2026-11-18T14:33:21+00:00 web-1 patch-server[3727]: 2026-11-18T14:33:21Z patch-server: health check passed: http://127.0.0.1/ answers 'bookshop is up'
2026-11-18T14:33:21+00:00 web-1 patch-server[3727]: 2026-11-18T14:33:21Z patch-server: a reboot is needed to finish, for:
2026-11-18T14:33:22+00:00 web-1 hc-ping[38009]: hc-ping: told Healthchecks.io the run ended with 0 (success)
2026-11-18T14:33:22+00:00 web-1 systemd[1]: Finished patch-server.service - Install updates, restart the bookshop, and check it still works.
- About 90 seconds, start to finish.
- "updated 272 packages", more than the 245 pending, because
--with-new-pkgsadded the new kernel's packages. - nginx restarted, and the health check passed. The bookshop works on the patched server.
- "a reboot is needed to finish, for:" and then nothing. Ubuntu didn't write down which packages asked for the reboot. That's why the script you have now also compares kernels, and names the new one.
hc-pingreported success to Healthchecks.
Reboot
A new kernel is installed but not running until the server restarts. Check for yourself:
ls /boot/vmlinuz-*
uname -r
sudo reboot
/boot/vmlinuz-6.8.0-149-generic /boot/vmlinuz-6.8.0-86-generic
6.8.0-86-generic
Broadcast message from root@vagrant on pts/1 (Wed 2026-11-18 14:38:57 UTC):
The system will reboot now!
ls /boot/vmlinuz-*: lists the installed kernels.vmlinuzis the kernel file, and*matches any version. Two are installed: the old one and the new one.uname -r: the running one is still the old one, 86.sudo reboot: restart the server. Your session ends.
This is the gap that catches people out. A server can have every security fix installed and still be running the old, vulnerable kernel, for months, because nobody rebooted it. "Installed" isn't "running". The only way to finish is to reboot.
Log back in with vagrant ssh from your own computer, then:
uname -r
sudo patch-server --check
apt list --upgradable 2>/dev/null | grep -c 'upgradable from'
6.8.0-149-generic
2026-11-18T14:40:45Z patch-server: health check passed: http://127.0.0.1/ answers 'bookshop is up'
0
The new kernel is running, the bookshop came back on its own, and nothing is left to update. nginx was held, but it had nothing waiting anyway: it was installed new when the server was built. The login message changed too, from Ubuntu 24.04.3 to 24.04.5.
Break it
Now the failure patching is really about. Someone added a config file to nginx weeks ago, and never tested it. nginx only reads its config when it starts, so it carries on running the old config, and nobody notices:
echo "this is not nginx config" | sudo tee /etc/nginx/conf.d/notes.conf
curl -s http://127.0.0.1/; echo
this is not nginx config
<h1>The bookshop</h1><p>bookshop is up</p>
echo "..." | sudo tee FILE: writes the text into a file only root can write to.teewrites what it receives into the file, and prints it too. (sudo echo "..." > FILEdoesn't work, because the>runs as you, not root.)curl -s: fetches the page.-shides the progress bar. The site still works. The broken file is there, waiting.
Then the patch job runs:
sudo systemctl start patch-server.service
journalctl -u patch-server.service --no-pager -o short-iso | tail -12
sudo nginx -t
Job for patch-server.service failed because the control process exited with error code.
2026-11-18T14:41:27+00:00 web-1 patch-server[1174]: 2026-11-18T14:41:27Z patch-server: nothing to update
2026-11-18T14:41:27+00:00 web-1 patch-server[1174]: 2026-11-18T14:41:27Z patch-server: restarting nginx, so a problem shows now and not at the next reboot
2026-11-18T14:41:27+00:00 web-1 systemctl[1442]: Job for nginx.service failed because the control process exited with error code.
2026-11-18T14:41:27+00:00 web-1 patch-server[1174]: 2026-11-18T14:41:27Z patch-server: nginx didn't restart; see: journalctl -u nginx
2026-11-18T14:41:37+00:00 web-1 patch-server[1174]: 2026-11-18T14:41:37Z patch-server: health check FAILED: http://127.0.0.1/ didn't answer 'bookshop is up' after 5 tries
2026-11-18T14:41:37+00:00 web-1 systemd[1]: patch-server.service: Main process exited, code=exited, status=1/FAILURE
2026-11-18T14:41:38+00:00 web-1 hc-ping[1464]: hc-ping: told Healthchecks.io the run ended with 1 (exit-code)
2026-11-18T14:41:38+00:00 web-1 systemd[1]: Failed to start patch-server.service - Install updates, restart the bookshop, and check it still works.
2026/11/18 14:41:38 [emerg] 1475#1475: unexpected end of file, expecting ";" or "}" in /etc/nginx/conf.d/notes.conf:2
nginx: configuration file /etc/nginx/nginx.conf test failed
- The restart made nginx read its config, and it refused to start.
- The health check failed 5 times in 10 seconds, the job exited 1, and
hc-pingtold Healthchecks so. nginx -ttests the config without restarting anything, and names the problem: the file and the line.
The patch didn't break the bookshop. It found a problem that was already there. Without the restart, it would have surfaced at the next reboot, perhaps at 3am after a power cut, with nobody expecting it. This way it surfaced during the maintenance window, with a clear message and an alert.
Fix it, and run the job again:
sudo rm /etc/nginx/conf.d/notes.conf
sudo nginx -t
sudo systemctl start patch-server.service
journalctl -u patch-server.service --no-pager -o short-iso | tail -4
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
2026-11-18T14:42:32+00:00 web-1 patch-server[1486]: 2026-11-18T14:42:32Z patch-server: health check passed: http://127.0.0.1/ answers 'bookshop is up'
2026-11-18T14:42:32+00:00 web-1 hc-ping[1756]: hc-ping: told Healthchecks.io the run ended with 0 (success)
Who tells you
A patch run that fails at 3am on a Sunday is only useful if someone finds out. Every run reports itself to Healthchecks.io, a free service that watches scheduled jobs.
How it works
In Healthchecks, each job gets a check, with its own secret web address, its ping URL. After every run, hc-ping visits that address with the run's exit code on the end: /0 for success, /1 for failure. Healthchecks then:
- sends an alert at once when it gets a failure, and
- sends an alert when nothing arrives in time, in case the job stopped running at all.
"In time" is set by two numbers on the check: the period, how often the job runs, and the grace time, how long to wait after a late run before raising the alarm.
This is hc-ping, the same small script for any job: it reads the URL from a file, turns systemd's description of how the run ended into an exit code, and sends it.
#!/usr/bin/env bash
# hc-ping: tell Healthchecks.io how the service's last run ended.
#
# systemd runs this after every run (ExecStopPost), and sets SERVICE_RESULT
# (success, exit-code, timeout, signal...) and EXIT_STATUS (a number, or a
# signal name like TERM). Healthchecks.io takes a number on the end of the
# ping URL: 0 means it worked, anything else means it failed.
#
# The ping URL is a secret (anyone with it can mark the check up or down), so
# it's read from a file, HC_URL_FILE, and never printed.
set -euo pipefail
url_file=${HC_URL_FILE:-/etc/hc-ping/ping-url}
if [ ! -r "$url_file" ]; then
echo "hc-ping: no ping URL in $url_file, so not telling anyone" >&2
exit 0
fi
url=$(tr -d '[:space:]' <"$url_file")
if ! [[ $url =~ ^https://hc-ping\.com/[A-Za-z0-9_/-]+$ ]]; then
echo "hc-ping: $url_file doesn't hold a Healthchecks.io ping URL, so not telling anyone" >&2
exit 0
fi
result=${SERVICE_RESULT:-unknown}
code=${EXIT_STATUS:-1}
if [ "$result" = success ]; then
code=0
elif ! [[ $code =~ ^[0-9]+$ ]] || [ "$code" -eq 0 ]; then
code=1 # killed by a signal or a timeout: no exit code, but still a failure
fi
if curl -fsS -m 10 --retry 3 -o /dev/null "$url/$code"; then
echo "hc-ping: told Healthchecks.io the run ended with $code ($result)" >&2
else
echo "hc-ping: couldn't reach Healthchecks.io" >&2
fi
SERVICE_RESULTandEXIT_STATUS: systemd sets these forExecStopPost.SERVICE_RESULTsays how the run ended (success,exit-code,timeoutand others), andEXIT_STATUSholds the exit code.curl -fsS -m 10 --retry 3 -o /dev/null: fail on an error (-f), stay quiet unless something goes wrong (-sS), give up after 10 seconds (-m 10), try three more times if the network blips (--retry 3), and throw away the reply (-o /dev/null).- It always exits 0, even when it can't reach Healthchecks, so a problem with the monitoring never marks the job itself as failed.
hc-ping runs from ExecStopPost=, which systemd runs after every run, however it ended: finished, failed, crashed or stopped for taking too long. A line at the end of the script itself would be skipped in exactly the cases that matter most.
The ping URL is a password. Anyone with it can mark the check up or down. So it's kept in a file only root can read, /etc/patch-server/ping-url, and never printed. In the practice folder, it goes in .healthchecks-url, which Git ignores. To put it there without it ever showing on screen:
read -rs HC && printf '%s\n' "$HC" > .healthchecks-url && unset HC
read -rs HC: waits for you to paste one line into a variable calledHC.-shides what you paste;-rkeeps backslashes as they are.&&: run the next command only if this one worked.printf '%s\n' "$HC" > .healthchecks-url: writes it into the file, with a new line at the end.unset HC: forgets it.
Run that first, then copy the URL and paste it. If you copy the URL first, then copy the command, your clipboard holds the command when you paste. setup.sh checks the file starts with https://hc-ping.com/ and refuses it otherwise, which is how I found that I'd done exactly that.
The settings have to match the job
My first try at this lab sent the wrong alerts. The ping URL in the file belonged to an old check from another job, with a 5-minute period. Here's what happened, in New York time:
| Time | What happened |
|---|---|
| 9:33:22 | The patch run ended, and reported success |
| 9:39:22 | A DOWN email: "success signal did not arrive on time, grace time passed" |
| 9:41:38 | The broken-config run reported failure. No email: the check was already down |
| 9:42:32 | The fixed run reported success: an UP email |
The DOWN email came two minutes before anything broke. The check expected to hear from the job every 5 minutes; a weekly job is silent for 7 days, so after 6 minutes (5 of period, 1 of grace) it called the job dead. Then the real failure arrived while the check was already down, and was lost in the noise.
Two rules come out of that:
- One job, one check. A check shared with another job, or left over from one, tells you about the wrong thing.
- The period matches the job's schedule. For a weekly job, the period is 7 days. The grace time is how late is too late: an hour is reasonable for a job that takes a few minutes.
The right check
With a new check, web-1 patching, period 7 days, grace 1 hour, the same break gave a clean result. The email arrived the same second the run failed:
DOWN | web-1 patching
"web-1 patching" is DOWN (received a failure signal).
Period: 1 week Total Pings: 1
Last Ping: now, from (your IP) Last Ping Type: Exit status 1
Status Changed to Down at: Wed, 18 Nov 2026 09:53:51 -0500
- "received a failure signal": the job said it failed, so Healthchecks didn't wait for anything.
- Exit status 1: the code
hc-pingsent. - "from (your IP)": each ping shows the public address of the network the server is on. Worth knowing before you share a screenshot of one.
And after the fix:
UP | web-1 patching
"web-1 patching" is UP. The downtime lasted 6 minutes, 56 seconds.
Last Ping Type: Exit status 0
Status Changed to Up at: Wed, 18 Nov 2026 10:00:48 -0500
(That run happened on a fresh copy of the server, so before failing, it installed all 245 updates first. A patch run on a server with a broken config hiding in it: about as realistic as it gets.)
If the job stops running
If the timer is switched off, or the server is down on Sunday, there's no run, so nothing is reported. That's where the period and grace come in: when Sunday 03:00 plus a week plus an hour passes with no ping, Healthchecks sends a DOWN email saying the signal "did not arrive on time". Nothing on the server can tell you a job didn't run, because there's nothing running to tell you. Only something outside it, expecting to hear, can notice the silence.
Undo
Patching went fine here. When it doesn't, the fastest fix is often to go back to before. That's what the snapshot was for. Leave the server (exit), then on your own computer:
vagrant snapshot restore before-patch
vagrant ssh -c "uname -r; apt list --upgradable 2>/dev/null | grep -c 'upgradable from'"
vagrant destroy -f
==> default: Restoring the snapshot 'before-patch'...
...
6.8.0-86-generic
245
==> default: Stopping the VMware VM...
==> default: Deleting the VM...
vagrant snapshot restore before-patch: puts the whole server back exactly as it was when you saved the snapshot.vagrant ssh -c "...": logs in, runs the commands in quotes, and logs out.;separates the two commands.vagrant destroy -f: deletes the server.-fskips the "are you sure?" question.
The old kernel, 86, and all 245 updates waiting again. Every patch undone in under a minute. Cloud servers have the same idea: a snapshot of the disk, or an image of the whole server, taken just before patching.
Then, in Healthchecks, delete the web-1 patching check.
In real life: an email after every run
A very common setup is a script that emails its log after every run, success or failure. It's a good start: you get the detail, every time. It has three gaps:
- If the script never runs, no email comes, and a quiet inbox looks the same as a quiet night.
- If the server's email setup breaks, the failure email never leaves the server, and nobody knows.
- After a few weeks of "it worked" emails, people stop reading them, and the one failure email gets skimmed past with the rest.
A heartbeat check closes all three: the alarm comes from outside the server, and only when something's wrong. The two work well together: the email for the detail, the heartbeat to tell you when the emails have stopped.
On a real server
- Patch a test server first. The same updates on a copy of production, a few days earlier, catch most surprises before they matter.
- Take a snapshot or image before patching, so undoing is one command, not an afternoon.
- Decide how reboots happen. Either the patch job reboots in the window, or
unattended-upgradesdoes (itsAutomatic-Rebootsetting), or a person does, on a schedule. "Whenever someone remembers" means a vulnerable kernel for months. - Health-check what users actually use: the real page, the real login, not just "is the process running".
- Spread patching out across many servers, a few at a time, and stop if one fails its check. Patching many servers at once is Lesson 5, with Ansible.
- Track holds. Every held package needs a reason and a date to review it.
Spot the problem
Work out what's wrong before you read the explanation.
"We patch every week. How did we fail the audit?" A team's servers run a patch script every Sunday. It reports success every week, and every report shows the latest updates installed. A security audit flags a server as vulnerable to a kernel hole that was fixed eight months ago. The team checks: the fixed kernel is installed. What's wrong? The fixed kernel is installed, but the server hasn't rebooted in eight months, so it's still running the old one. ls /boot/vmlinuz-* shows the new kernel; uname -r shows the old one. Their script installs updates and stops there. The fix: make rebooting part of patching: in the maintenance window, by the script, by unattended-upgrades, or by a person on a schedule. Then report when the running kernel isn't the newest installed one, as patch-server does, so it can't hide.
Keep this
| To | Use |
|---|---|
| Refresh the list of available updates | sudo apt-get update |
| Count pending updates | apt list --upgradable 2>/dev/null | grep -c 'upgradable from' |
| Count pending security updates | apt list --upgradable 2>/dev/null | grep -c -- '-security' |
| Install updates, with no questions | sudo DEBIAN_FRONTEND=noninteractive apt-get -y --with-new-pkgs upgrade |
| Hold or release a package | sudo apt-mark hold PKG, sudo apt-mark unhold PKG |
| List held packages | apt-mark showhold |
| Is a package installed? | dpkg -l PKG |
| Are automatic updates on? | systemctl list-timers 'apt-daily*' |
| The running kernel, and the installed ones | uname -r, ls /boot/vmlinuz-* |
| Test nginx's config without restarting | sudo nginx -t |
| Follow a service's log live | journalctl -u NAME -f |
| Save and restore a Vagrant server | vagrant snapshot save NAME, vagrant snapshot restore NAME |
Where you are now
You've patched a real server from 245 waiting updates to none, with a script that restarts the app and checks it after every run, rebooted it for a new kernel and checked again, and found a hidden broken config the moment the patch run restarted nginx. You got an alert within a second of the failure, saw what a badly set check does, and undid the whole thing with one command. Lesson 3 builds the checks that run all the time, not just after patching: the site is down, the disk is filling up, the certificate is about to expire.
Check yourself
The server had 245 updates waiting. Why hadn't it installed them itself?
Why does the patch script restart nginx even when nginx wasn't updated?
'Warning! D-Bus connection terminated' appeared during the patch run. What happened?
Every security update is installed, but uname -r shows an old kernel. What's needed?
A weekly job reports to a check with a 5-minute period. What happens?
Why does hc-ping run from ExecStopPost, not as the script's last line?
Key terms
- Patch: an update that fixes a problem, often a security hole, in software that's already installed.
- Kernel: the core of the operating system. A new one only runs after a reboot.
- Maintenance window: a regular, agreed time for changes like patching, when a short outage hurts least.
- Hold: telling
aptnot to update a package until you release it. - Health check: a test that the app actually works, like fetching its page and checking what it says.
- Snapshot: a saved copy of a whole server, which you can go back to.
- Heartbeat check: an outside service that expects to hear from a job, and raises an alarm on a failure or on silence.
- Period and grace time: how often a check expects to hear from a job, and how long it waits after a late one.
Go deeper
- Earlier lessons: Installing software for
apt, Services and logs with systemd forsystemctlandjournalctl, and Shell scripts and cron, done properly for timers. - UnattendedUpgrades on the Debian wiki (opens in a new tab), for setting up automatic security updates, including automatic reboots.
- The US Government Accountability Office's report on the Equifax breach (opens in a new tab), on how an unpatched hole led to it.
- Healthchecks.io documentation (opens in a new tab), on exit-code pings, schedules and alert channels.
- Manuals:
man apt-get,man apt-markandman systemd.timer, on any Ubuntu machine. - Try: hold
opensslbefore patching, and check the dry run says it won't be updated. Then change the timer toOnCalendar=*-*-* 03:00:00 UTC, every day, and work out what the Healthchecks period should become.