Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Ansible - Update Debian Based Systems

One of the main reasons to deploy an Ansible server is to update all of your servers whenever there is a critical security update such as the heartbleed bug. Today we will show you how to do precisely that for servers that use apt, such as debian and ubuntu.

Hosts File

The first thing we need to do is define a grouping of all the servers we wish to update through ansible, by updating our ansible hosts file. For this tutorial, I am going to refer to them simply as apt_servers because all these servers use the apt system to perform updates.

[apt_servers]
svn.programster.org
192.168.1.1

[yum_servers]
192.168.1.5
yum.programster.org

I used to use - instead of _ but ansible complained about invalid characters, so be sure to use camelCase or snake_case when setting the group names.

Create the Playbook

Next we need to create a playbook to tell Ansible what we want to do. Playbooks are in the YAML format so we suffix them with .yml but you dont have to. For this tutorial, I am going to call it update-apt-servers.yml. Fill it with the following contents if you just want to perform updates.

- hosts: apt_servers
  become: true
  tasks:
   - name: updates a server
     apt: update_cache=yes
   - name: upgrade a server
     apt: upgrade=dist

You can replace upgrade=dist with upgrade=full, please refer here if you want to know the difference. Older ansible versions used to use sudo: true instead of become: true.

If you wish to take this a step further and perform a reboot if required for the updates to be applied, then you can use this script:

- hosts: apt_servers
  become: true
  tasks:
   - name: updates a server
     apt: update_cache=yes
   - name: upgrade a server
     apt: upgrade=dist
   - name: Check if a reboot is required
     register: file
     stat: path=/var/run/reboot-required get_md5=no
   - name: Reboot the server
     command: /sbin/reboot
     when: file.stat.exists == true

Execute!

Now we have the hosts and playbook defined, we can execute the update.

export ANSIBLE_HOSTS="$HOME/ansible/ansible_hosts"
ansible-playbook update-servers.yml --ask-sudo-pass
  • This will try to log in as the same user you are currently logged in as on the ansible host. If you want to log in as a different user, append: --user=[username]
  • Executing playbooks requires the Ansible server to have SSH key access to the other hosts.
  • Remove --ask-sudo-pass if you have configured your slaves to not require sudo password.

References

Last updated: 19th January 2025
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch