Updated Ubuntu/Debian update ansible script
---
- hosts: all
  gather_facts: yes
  become: yes
  serial: 1

  tasks:
    - name: Perform a dist-upgrade.
      ansible.builtin.apt:
        upgrade: dist
        update_cache: yes

    - name: Check if a reboot is required.
      ansible.builtin.stat:
        path: /var/run/reboot-required
        get_md5: no
      register: reboot_required_file

    - name: Reboot the server (if required).
      ansible.builtin.reboot:
      when: reboot_required_file.stat.exists == true

    - name: Wait for Machine to come back online
      local_action: wait_for
             host={{ inventory_hostname }}
                port=22
                state=started
                delay=65
      when: reboot_required_file.stat.exists == true

    - name: Remove dependencies that are no longer required.
      ansible.builtin.apt:
        autoremove: yes

~                              

The above is an improvement on the previous version, thanks to Jeff Geerling. This version checks to see if a reboot is required then waits for the server to come back online.

Ansible code to update all Raspberry Pi

The following code will one by one update your raspberry Pis and then reboot them.



---
- hosts: all
remote_user: pi
serial: 1

tasks:
– name: Update all packages
apt:
upgrade: dist
update_cache: yes
become: yes
register: updated

– name: Reboot Machine if updated
command: shutdown -r +1
async: 1
poll: 0
ignore_errors: true
become: yes
when: updated.changed

– name: Wait for Machine to come back online
local_action: wait_for
host={{ inventory_hostname }}
port=22
state=started
delay=65
when: updated.changed
~