Skip to content
masdzub.com
~/articles/debian — one from the notebook

Set Up Automatic Security Updates with unattended-upgrades on Debian 12

Configure unattended-upgrades on Debian 12: origins, blacklists, reboot policy, mail reports, log checks, and fixes for failed silent patching.

masdzub@website:~$ cat ~/articles/set-up-automatic-security-updates-with-unattended-upgrades-on-debian-12.aspx.md
# 1 file · 19 min read · topic: debian · status: published

Introduction

You get automatic Debian security updates on version 12 by installing unattended-upgrades, enabling the two APT periodic hooks, restricting Origins-Pattern to the Debian and Debian-Security archives for your codename, then configuring reboot and mail behavior in /etc/apt/apt.conf.d/50unattended-upgrades. The default configuration already pulls only from Debian and Debian-Security for the running release, so third-party repositories are left alone unless you add them yourself. Everything below assumes root access, a standard sources.list, and no configuration management tool overriding APT’s periodic hooks.

How the update chain runs on Debian 12

The scheduler lives in the apt package, not in unattended-upgrades. Two systemd timers do the work. apt-daily.timer starts apt-daily.service around 06:00 local time with up to 12 hours of randomized delay, and apt-daily-upgrade.timer starts apt-daily-upgrade.service with about an hour of randomization on top of the same nominal hour. Both units execute /usr/lib/apt/apt.systemd.daily, a shell script that reads the APT::Periodic::* settings from /etc/apt/apt.conf.d/20auto-upgrades and decides whether to refresh package lists, download upgrades, or run the actual upgrade. When APT::Periodic::Unattended-Upgrade is set to 1, that script calls /usr/bin/unattended-upgrade, the Python program from the package of the same name.

The unattended-upgrades.service unit that appears in systemctl status is not the scheduler. It stays running and waits for a shutdown signal so the system can check for pending upgrades before it powers off. Confusing the two is a common reason people think automatic upgrades are broken when the real problem is a stopped timer.

Confirm the timers before changing anything:

Terminal window
systemctl list-timers 'apt*'
systemctl status apt-daily.timer apt-daily-upgrade.timer

You should see both timers active with a next-elapse time inside the next 24 hours. If they report inactive (dead), they were disabled, usually by a hardening script or an image build that ran systemctl disable.

Install and enable the two packages

On a stock Debian 12 install, installing the package pulls in its recommends, which include apt-listchanges, a mail transport agent, and needrestart. Those three are worth keeping.

Terminal window
apt update
apt install unattended-upgrades apt-listchanges

apt-listchanges is the piece that embeds changelog text into the report email, so a security update arrives with a short explanation of what changed instead of a bare package list. needrestart checks whether any running service is still linked against an old library after the upgrade and is covered later.

Then run the debconf front end, which writes the periodic hook file:

Terminal window
dpkg-reconfigure --priority=low unattended-upgrades

The prompt asks whether to download and install upgrades automatically. Answering yes writes both APT::Periodic switches to 1. Answering no writes the same lines with 0, which is a silent disable. If you prefer to skip debconf, create /etc/apt/apt.conf.d/20auto-upgrades by hand with the content in the next section, then enable the timers:

Terminal window
systemctl enable apt-daily.timer apt-daily-upgrade.timer

On a default Debian 12 install the timers are already enabled, so this is a no-op unless something disabled them.

The two files that control behavior

20auto-upgrades holds only the periodic switches. 50unattended-upgrades holds everything that decides which packages get applied and how the run behaves. APT parses files in /etc/apt/apt.conf.d in lexical order, and a later file overrides a scalar set in an earlier one, which is why 50 wins over 20 when both define a key.

A minimal and complete 20auto-upgrades looks like this:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Download-Upgradeable-Packages "1";

Update-Package-Lists refreshes apt-get update output once a day. Unattended-Upgrade runs the upgrade step. AutocleanInterval "7" runs apt-get autoclean weekly, which removes cached .deb files for versions no longer in the archive. Download-Upgradeable-Packages "1" pre-fetches the packages during the update phase so the upgrade phase spends its time running dpkg rather than waiting on the network, which also lowers the chance a slow mirror leaves the system half-finished at the end of the window. On a metered link, or on a very small VM with limited disk, drop that last line.

Do not put Origins-Pattern or Package-Blacklist in 20auto-upgrades. Those keys are read by unattended-upgrade itself when it starts, and the conventional home for them is 50unattended-upgrades. Keeping the two files separate also means a future dpkg-reconfigure cannot overwrite your origin rules.

One detail that catches people: /etc/apt/apt.conf.d/50unattended-upgrades is itself a conffile shipped by the package. If you edit it and a later package version changes it, dpkg will prompt you during a manual upgrade and leave a .dpkg-dist file. That is expected. Do not delete the .dpkg-dist blindly; diff it against your version first, since the packaging may have added a new origin line or a new default.

Match the right repositories with Origins-Pattern

The Origins-Pattern block is where the security policy actually lives. It uses match strings built from the Release file fields that APT already knows: origin, codename, label, archive, suite, and component. Debian 12 ships three active patterns:

Unattended-Upgrade::Origins-Pattern {
"origin=Debian,codename=${distro_codename},label=Debian";
"origin=Debian,codename=${distro_codename},label=Debian-Security";
"origin=Debian,codename=${distro_codename}-security,label=Debian-Security";
};

${distro_codename} is expanded at runtime from the release information, so the file keeps working after an upgrade from bookworm to trixie. On bookworm, the second line is effectively dead because no archive reports codename=bookworm together with label=Debian-Security. The third line is the one that matches the security archive, where the codename is bookworm-security. Leaving the second line in place is harmless and Debian keeps it for compatibility with older point releases.

Verify the origin strings your mirrors actually advertise before trusting any pattern you copy from a blog post:

Terminal window
apt-cache policy | grep release

Each line looks like release v=12.10,o=Debian,a=stable,n=bookworm,l=Debian,c=main,b=amd64, and the o=, a=, n=, and l= fields map directly to origin, archive, codename, and label in the pattern syntax. If your mirror is a local Snapshot or an internal aptly proxy, its origin may be something other than Debian, and a pattern copied from elsewhere will silently match nothing. That is the single most common reason a system looks configured but never applies a security update.

For a third-party repository, adding it is possible but easy to regret. A pattern such as "origin=Docker,codename=${distro_codename},label=Docker CE" will apply every package upgrade the vendor publishes, including new upstream feature releases that were never tested against your application. Only add a third-party origin if the vendor separates security fixes from feature releases and you accept the vendor’s stability guarantees. Most teams get better results by leaving third-party repos out of unattended upgrades and handling them through their normal release process.

Confirm the effective set after editing:

Terminal window
unattended-upgrade --dry-run --debug | grep -i "allowed origins"

The output prints the expanded origin strings that were actually parsed, which is the ground truth for what the next run will consider.

Hold back packages that need a human

Package-Blacklist takes a list of regular expressions matched against package names. A package matching the list is skipped during the unattended run, even if its origin is allowed. This is the mechanism to keep a stateful service or a risky package on a manual cadence:

Unattended-Upgrade::Package-Blacklist {
"linux-image";
"linux-headers";
"docker-ce";
"mysql-server";
"postgresql";
};

Blacklisting linux-image keeps the running kernel in place, which means a kernel security patch waits for the next maintenance window. That is a deliberate trade: you get controlled reboot timing at the cost of patch latency. On a host that can survive a reboot, leave kernels off the blacklist and let them flow through with an automated reboot window instead. Holding the kernel while letting everything else upgrade is a common pattern on single-instance database servers, but it does mean the CVE in the kernel image stays open until someone acts.

Two interactions are worth knowing. First, apt-mark hold is stronger than this list. A held package is not a candidate for any APT operation, so unattended-upgrades cannot touch it either, and apt-mark showhold is the place to check when a package refuses to move. Second, when a blacklisted package would have pulled in a dependency upgrade, APT keeps the dependency at its current version too. One over-broad regex can therefore freeze more than intended. Test the effect with apt-get -s dist-upgrade and compare the proposed set against what you meant to allow.

Package-Whitelist exists as an allowlist, but the way it interacts with Origins-Pattern is confusing enough that most admins use the blacklist alone. If you need a strict allowlist, drive it from configuration management and test carefully, because an empty or misparsed whitelist will quietly reduce the set to nothing.

Make dpkg noninteractive without losing conffiles

unattended-upgrade sets DEBIAN_FRONTEND=noninteractive and APT_LISTCHANGES_FRONTEND=none for the child processes, so debconf questions do not block the run. dpkg conffile prompts are a separate mechanism, and the default behavior under noninteractive mode is to keep the currently installed configuration file and write the new one alongside it with a .dpkg-dist suffix. The package upgrades, the service may restart with the old config, and nobody is told. That silent divergence is the biggest long-term risk of automatic upgrades on a hand-managed host.

Make the choice explicit by adding a Dpkg::Options block. In 50unattended-upgrades:

Dpkg::Options {
"--force-confdef";
"--force-confold";
};

--force-confdef tells dpkg to take the default action where one exists, and --force-confold keeps the old file when a modified conffile conflicts with the maintainer version. The result is deterministic and non-hanging. The cost is the same one described above: the new maintainer config lands as *.dpkg-dist and a human still has to merge it.

If you would rather apply the maintainer version everywhere, swap to --force-confnew. That keeps packages and configs in sync but overwrites local edits, which is disastrous on anything with hand-tuned settings. Neither option is universally right; the important part is picking one on purpose and documenting it.

Also set:

Unattended-Upgrade::AutoFixInterruptedDpkg "true";

This makes the run call dpkg --configure -a when it detects an interrupted dpkg state, which recovers from a crashed previous run instead of failing every subsequent one.

Reboot policy, kernels, and needrestart

A kernel or glibc update only takes effect after a reboot. Debian flags the need by creating /var/run/reboot-required, and unattended-upgrade checks for that file when Automatic-Reboot is true:

Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
Unattended-Upgrade::Automatic-Reboot-WithUsers "false";

Automatic-Reboot-WithUsers "false" is the safe default. The upgrade run checks /run/utmp for logged-in users, and if anyone is connected it skips the reboot and logs that fact. The reboot then waits for the next successful run. On an unattended server that nobody logs into, setting it to true lets the reboot proceed, which is usually what you want.

The flag file matters. On a minimal image, /var/run/reboot-required may never appear because the hook that writes it is missing. After a kernel upgrade, check:

Terminal window
ls -l /var/run/reboot-required*
cat /var/run/reboot-required.pkgs 2>/dev/null

If the file is absent on a system that clearly needs a reboot, install update-notifier-common, which ships the post-install hook that writes it. Without the flag, Automatic-Reboot "true" will never trigger.

needrestart covers the services that are not fixed by a reboot check. After a libssl, libc, or libpam upgrade, a running daemon may still hold the old library in memory. needrestart detects that and, in unattended mode, lists the affected services without restarting them by default. To let it restart them, edit /etc/needrestart/needrestart.conf:

$nrconf{restart} = 'a';

The 'a' value means automatic restart. Be aware of what that implies: an sshd or nginx restart during business hours will drop connections and in-flight requests. For stateful services, the safer path is to leave needrestart in list-only mode and restart on your own schedule.

Optionally, clean up after kernel upgrades:

Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";

The first removes old kernel images and their headers after a successful upgrade, which prevents /boot from filling up on long-lived VMs. The second runs apt-get autoremove for orphaned dependencies. Both are safe on normal systems and both can surprise an admin who expected to boot an older kernel for rollback, so decide deliberately.

Email reports that you will actually read

Nothing is more useless than a silent patching system that has been failing for six weeks. Set up mail:

Unattended-Upgrade::Mail "root";
Unattended-Upgrade::MailReport "on-change";

MailReport "on-change" sends a message only when packages were actually upgraded or an error occurred, which means the absence of mail is the healthy signal. The older MailOnlyOnError "true" is still supported and behaves similarly for errors; MailReport also covers successful changes. The default, always, sends a report after every run, including empty ones, and most people stop reading it within a week.

The mailer needs a working local MTA. On a minimal image, check:

Terminal window
command -v sendmail
echo "test" | sendmail -t root@example.com

If sendmail is missing, apt install bsd-mailx pulls in default-mta, which on Debian is exim4-daemon-light. Configure it for local delivery if you only need root mail, or as a satellite relay if you forward to a central mailbox. mailutils is an alternative that provides the same interface. Whatever you pick, verify a test message lands before you trust the reports.

Check /var/log/mail.log when the run finishes but no message appears. A common failure on fresh images is that the MTA is installed but not configured, so sendmail exits non-zero and the report is dropped. The unattended-upgrades log will record a mail-sending failure at the end of the run, which is easy to miss if you only watch for package errors.

Test the whole chain before trusting it

You can exercise the entire pipeline without applying anything. Run as root:

Terminal window
unattended-upgrade --dry-run --debug

The output is chatty. Read it in this order:

  • The Allowed origins are: line confirms the origin patterns expanded correctly for your codename.
  • The Packages that will be upgraded: line is the set the real run would apply. If it is empty and you expected a security update, the cause is almost always an origin mismatch, a blacklist hit, or a held package.
  • The Checking: lines under --debug show each package the solver considered, which is useful when a package is unexpectedly excluded.

Cross-check with a plain simulation:

Terminal window
apt-get -s dist-upgrade

This shows the full pending set, regardless of origin policy. If a package appears here but not in the unattended dry run, the difference is policy, not availability.

Then run the timer-driven path on purpose, so you test what systemd actually executes:

Terminal window
systemctl start apt-daily-upgrade.service
journalctl -u apt-daily-upgrade.service --since "10 minutes ago"

Watch the exit status in the journal. A 0 with a short package list is a successful run. A non-zero status means something in the chain failed, and the log file path below points at the reason.

Finally, confirm the periodic config is actually being read:

Terminal window
apt-config dump APT::Periodic

Every switch should print with the expected value. If APT::Periodic::Unattended-Upgrade shows "0", the run will never happen no matter how correct the rest of the file is.

Read the logs

There are four logs worth knowing, and each answers a different question.

/var/log/unattended-upgrades/unattended-upgrades.log is the main event log. It records the resolved origins, the blacklist, the package set, the per-package progress, and any error strings. Start here when a run misbehaves.

/var/log/unattended-upgrades/unattended-upgrades-dpkg.log captures the raw dpkg output. If a package postinst fails, or a conffile prompt would have appeared, this file holds the detail.

/var/log/apt/history.log records every APT transaction, including the unattended ones, with the full package list and the command line. It is the canonical record of what changed and when.

/var/log/apt/term.log holds the terminal output from those transactions, which is useful when history.log shows an install but you need the exact error text.

Rotate the unattended-upgrades logs if your host runs for months. The package does not always ship a logrotate fragment, so verify with ls /etc/logrotate.d/ | grep -i unattended and add a small config if it is missing, keeping a few weeks of history. Reboots and failures often get noticed weeks after the fact, and a log that grew to hundreds of megabytes is harder to search than one that was rotated.

For correlating with systemd, use:

Terminal window
journalctl -u apt-daily.service -u apt-daily-upgrade.service --since "7 days ago"

This is the right place to look when systemctl list-timers shows the timer ran but the unattended log shows nothing. That combination usually means the script exited early on a lock or a stale stamp file.

Troubleshooting the errors that stop silent patching

The dpkg lock is held

The log shows a message identical to this, sometimes followed by retrying:

E: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1834 (apt-get)

An interactive apt-get session is running, or a previous unattended run is stuck. Find the holder with fuser -v /var/lib/dpkg/lock-frontend and wait for it to finish. Do not delete the lock file. If the holder is a dead process, the correct recovery is to confirm no apt or dpkg process is alive, then remove the stale lock only as a last resort.

Conffiles silently diverged

No error appears, but a config edit is missing after an upgrade and /etc/<pkg>/<file>.dpkg-dist exists. This is the noninteractive conffile behavior described earlier. Either accept it and add the .dpkg-dist merge to your monthly review, or switch to --force-confnew on hosts where the maintainer config is authoritative. There is no third option that preserves both.

The upgrade is killed by the OOM killer

On a VM with 512 MB or 1 GB of RAM, the package install can be killed:

Out of memory: Killed process 4512 (apt-get) total-vm:812344kB

Check dmesg -T | grep -i oom. The fix is more memory or a swap file, not a config tweak. A 1 GB swap file on a small VM is usually enough, and it is worth adding before the first unattended run rather than after the first failure.

Mail never arrives

The run completes and packages upgrade, but no message appears. echo test | sendmail -t root is the first test. If it fails, the MTA is the problem, not unattended-upgrades. Check /var/log/mail.log and the MTA’s own logs. If it succeeds, check the recipient setting and whether MailReport "on-change" is suppressing an empty run. Also confirm the run actually reached the mail step; a crash mid-upgrade means no report at all, and the log is the only signal.

The timer runs but nothing upgrades

systemctl list-timers shows recent runs, yet no packages move. Check three things in order. First, apt-config dump APT::Periodic to confirm the switch is 1. Second, apt-cache policy <package> to confirm a newer candidate exists, because a pin or a snapshot mirror can hold it back. Third, apt-mark showhold to rule out a held package. If all three are clean, the origin pattern is the remaining suspect, and the Allowed origins are: line from the dry run will show it.

The reboot never happens

Automatic-Reboot "true" is set, a kernel was upgraded, but the host is still on the old kernel. Check who for logged-in users, because Automatic-Reboot-WithUsers "false" blocks the reboot in that case and logs it. Check ls /var/run/reboot-required*, because without the flag file the reboot is never requested. If both are clean, check the journal for the reboot step and confirm the configured Automatic-Reboot-Time has passed.

Operational trade-offs

Automatic security updates trade patch latency for control. The upside is real: the gap between a Debian security advisory and a running host shrinking from weeks to hours. The downside is real too. Security updates occasionally change behavior in ways that break a pinned application, particularly around openssl, glibc, sudo, and polkit. A release upgrade is not something unattended-upgrades does, but a point-release package update can still move a library version enough to matter.

Automatic reboot is the second trade. On a redundant fleet behind a load balancer, rebooting one node at 03:30 is routine. On a single-instance database or a hypervisor, it is an outage. Decide per host class rather than globally, and prefer Automatic-Reboot "false" with a monitored reboot-required alert on anything that cannot tolerate an unattended restart.

Conffile divergence is the third and the least visible. The package updates, the service keeps the old config, and the mismatch only surfaces when someone finally reads the .dpkg-dist file or the service starts failing after a later change. A monthly find /etc -name '*.dpkg-dist' catches most of it.

There is also the boundary: unattended-upgrades manages packages, not configuration. It will not reconcile /etc drift, rotate secrets, or deploy application code. Teams that expect it to replace a configuration management run eventually find a host with current packages and stale config, which is often worse than a host that is uniformly behind.

Finally, treat the mail channel as best-effort. A monitoring check on the log file’s last-modified timestamp, or on the age of the last successful entry, is more reliable than waiting for an email that may never be sent.

A baseline configuration

A working 50unattended-upgrades for a typical server:

Unattended-Upgrade::Origins-Pattern {
"origin=Debian,codename=${distro_codename},label=Debian";
"origin=Debian,codename=${distro_codename},label=Debian-Security";
"origin=Debian,codename=${distro_codename}-security,label=Debian-Security";
};
Unattended-Upgrade::Package-Blacklist {
"linux-image";
"linux-headers";
"docker-ce";
"mysql-server";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Dpkg::Options {
"--force-confdef";
"--force-confold";
};
Unattended-Upgrade::Mail "root";
Unattended-Upgrade::MailReport "on-change";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "03:30";
Unattended-Upgrade::Automatic-Reboot-WithUsers "false";

And the matching 20auto-upgrades:

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Download-Upgradeable-Packages "1";

Apply it with a syntax check, then run the dry run and the timer test from earlier:

Terminal window
apt-config dump > /dev/null && echo "config parses"
unattended-upgrade --dry-run --debug
systemctl start apt-daily-upgrade.service
journalctl -u apt-daily-upgrade.service --since "10 minutes ago"
tail -n 50 /var/log/unattended-upgrades/unattended-upgrades.log

If the Packages that will be upgraded: line matches what apt-get -s dist-upgrade proposes minus your blacklist, the configuration is doing what you told it to. Adjust the kernel and reboot lines per host class, and revisit the file after each Debian point release, because the shipped conffile can change and you want to see the diff before it becomes a surprise.

found this useful? share it →
Written by

Dzubayyan Ahmad

System Administrator, SRE & Technical Support Engineer specialising in web hosting infrastructure — Linux servers, automation, and monitoring. Writing these notes since 2015 so future-me can find the fix again.