Automated updates for Ubuntu 22.04 LTS (in packer etc)


For a long time I have seen that Ubuntu APT has declared it has not got a stable CLI interface and with 22.04LTS that has become a thing. If you try to a automate apt -y upgrade after an update your command will never complete as it will pop up a dialog window asking you which services you want to restart. Not very friendly for automation.
Now I don’t know if this the right way to do it, but it works for me in my homelab. What we do is leverage unattended-upgrade and change the settings before and after we run this command. By default unattended-upgrade is set only to apply security updates, something you want right. However, when you are creating a template usually you want all the other updates and patches that go with the default setup of your distro. So this is how I do it under packer with a shell script:

#!/bin/bash
sudo apt -y update
sudo sed -i '/${distro\_codename}/s/\\/\\//  /g' /etc/apt/apt.conf.d/50unattended-upgrades
sudo unattended-upgrade -d
sudo sed -i '/${distro\_codename}-updates/s/"${distro\_/\\/\\/"${distro\_/' /etc/apt/apt.conf.d/50unattended-upgrades
sudo sed -i '/${distro\_codename}-proposed/s/"${distro\_/\\/\\/"${distro\_/' /etc/apt/apt.conf.d/50unattended-upgrades
sudo sed -i '/${distro\_codename}-backports/s/"${distro\_/\\/\\/"${distro\_/' /etc/apt/apt.conf.d/50unattended-upgrades

We use sed to uncomment all the options, run unattended-upgrade and then revert the change. This is because we don’t want to have images built from this template to be automatically upgrading everything. If you really want that, just remove the sed lines after the upgrade command.

YMMV.