Updating Hosts with Ansible

Mon, Jan 25, 2021 One-minute read

One of the simplest Ansible playbooks I use in my home-lab is the one to update the packages on all of my Debian 10 (Buster) hosts:

- name: Update all packages to latest
  hosts: all
  become: yes
  tasks:
    - apt:
        name: '*'
        update_cache: yes
        state: latest
    - stat:
        path: /var/run/reboot-required
      register: reboot_required
    - reboot:
      when: reboot_required.stat.exists

It uses become to become a privileged user, updates all packages with the apt task (making sure it updates the package cache), checks for /var/run/reboot-required which is a signal that a reboot is required after an update (typically when the kernel is upgraded), and then reboots the host if required. Ansible will wait until the host returns from the reboot so you know whether or not it was successful.

Since YOLO I typically just run this playbook against all of my hosts at once:

ansible-playbook update.yaml -i inventory

If you’re more cautious you can run the playbook against a host group:

ansible-playbook update.yaml -i inventory -l web_servers

By default Ansible will run tasks in parallel against hosts, if you want to control how many hosts are updated at a time you can set the serial property for the play:

- name: Update all packages to latest
  hosts: all
  serial: 1
  become: yes
  tasks: