Note: In most scenario’s I would suggest manually installing updates so you have the extra flexibility of being in control of what updates, and when they update. There are however scenario’s where auto updating is useful. For example in a non production environment, where you have snapshotting in place or other means to easily revert to an earlier state if updates go badly. If you’re using LXD – See my LXD auto snapshotting article here to set that up.
First let’s prepare our system.
Install the unattended-upgrades package, along with cron.
sudo apt-get update && sudo apt-get install unattended-upgrades cron
Edit the unattended-upgrades config
nano /etc/apt/apt.conf.d/50unattended-upgrades
Uncomment or add in the repositories you want to auto update from. My example below is with a debian system, auto updating from the debian stable repository, and elastic.co repository.
"o=Debian,a=stable";
"o=Debian,a=stable-updates";
"o=elastic,a=stable";
Generate the auto-upgrades config
sudo dpkg-reconfigure unattended-upgrades
At this point, you’re done. The below delves a bit more into how this works, and what other options you have for customizing the cron job.
Determine when the system will auto update
The cron job for unattended-upgrade is stored in
/etc/cron.daily/apt
you can check the crontab config to see when the cron job will be run
nano /etc/crontab
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
From above we can see that cron runs daily cron jobs at 6:25am. You can edit this time if you want to change when cron daily runs, keep in mind that this will change the start time of any other daily cron jobs too.
Cron Job sleep time
The apt cron job automatically sleeps the cron job for a random amount of time within 30mins, to prevent all servers hitting the apt depos at once. You can edit the sleep window by editing the RamdomSleep value (Default is 1800 seconds) in the below section of /etc/cron.daily/apt
# sleep for a random interval of time (default 30min)
# (some code taken from cron-apt, thanks)
random_sleep()
{
RandomSleep=1800
eval $(apt-config shell RandomSleep APT::Periodic::RandomSleep)
if [ $RandomSleep -eq 0 ]; then
return
fi
if [ -z "$RANDOM" ] ; then
# A fix for shells that do not have this bash feature.
RANDOM=$(( $(dd if=/dev/urandom bs=2 count=1 2> /dev/null | cksum | cut -d' ' -f1) % 32767 ))
fi
TIME=$(($RANDOM % $RandomSleep))
debug_echo "sleeping for $TIME seconds"
sleep $TIME
}