reboot

Ansible: Update Servers to the Latest and Reboot

This is for Debian/Ubuntu flavored systems.

Keep a single server up to date is easy, but updating multiple servers at once, you need tools like Ansible. For each server, here is a list of basic steps:

  1. Check if there are packages available to be upgraded
  2. Upgrade all packages to the latest version
  3. Check if a reboot is required
  4. Reboot the server

When we log into the remote server, we might see the message showing the number of packages can be updated. The message is generated by:

1
2
3
4
$ sudo /usr/lib/update-notifier/update-motd-updates-available
25 packages can be updated.
18 updates are security updates.

And it is available at:

1
2
3
4
$ cat /var/lib/update-notifier/updates-available
25 packages can be updated.
18 updates are security updates.

We don’t need that detailed information, we just simply want to know if there are update available.

Shell script /usr/lib/update-notifier/apt-check shows any pending updates:

1
2
$ /usr/lib/update-notifier/apt-check
25;18

To list all the packages instead of simple packages;security format:

1
$ /usr/lib/update-notifier/apt-check --package-names

--package-names option will write data to stderr instead of stdout. If there are no packages needed to be installed, then the stderr should be empty.

If there are packages to be installed or upgraded. Ansible has the apt module to manage them in Debian/Ubuntu based systems.

1
2
3
4
5
6
7
- name: Check if there are packages available to be installed/upgraded
command: /usr/lib/update-notifier/apt-check --package-names
register: packages
- name: Upgrade all packages to the latest version
apt: update_cache=yes upgrade=dist
when: packages.stderr != ""

Restart Upstart Instances on System Reboot

A single Upstart job can have multiple instances running:

1
2
3
$ sudo start my-job port=4000
$ sudo start my-job port=4001
$ sudo start my-job port=4002

However, when the operating system reboots, the job with multiple instances will fail to start, due to instance information is not provided to the job. We can fix this problem by adding a for loop in the script section:

1
2
3
4
5
6
7
8
9
start on (local-filesystems and net-device-up IFACE!=lo)
stop on shutdown
script
for i in `seq 4000 4002`
do
exec /path/to/my/job
done
end script

With this Upstart job, we do not need to provide instance information:

1
$ sudo start my-job

Therefore, during system restart, the job will initiate automatically.