--- - name: Update and upgrade all packages hosts: all become: true tasks: - name: Gather facts ansible.builtin.setup: - name: Update the apt package index ansible.builtin.apt: update_cache: true - name: Upgrade all packages to the latest version ansible.builtin.apt: upgrade: dist - name: Autoremove unnecessary packages ansible.builtin.apt: autoremove: true - name: Clean up the apt cache ansible.builtin.apt: autoclean: true - name: Check if a reboot is required ansible.builtin.stat: path: /var/run/reboot-required register: reboot_required_stat - name: Reboot the system if a reboot is required ansible.builtin.reboot: msg: Reboot initiated by Ansible because updates require a restart connect_timeout: 5 reboot_timeout: 600 pre_reboot_delay: 0 post_reboot_delay: 30 when: reboot_required_stat.stat.exists == true - name: Wait for the system to come back online ansible.builtin.wait_for_connection: timeout: 300 when: reboot_required_stat.stat.exists == true - name: Display reboot result ansible.builtin.debug: var: reboot_required_stat when: reboot_required_stat.stat.exists == true