--- - hosts: yumhosts gather_facts: no tasks: - name: Update all installed packages using YUM module ansible.builtin.yum: use_backend: yum3 name: '*' state: latest update_cache: yes update_only: yes register: yum_update_status - name: Remove packages not needed anymore ansible.builtin.yum: use_backend: yum3 autoremove: yes - name: Check if a file exists ansible.builtin.stat: path: /var/run/needs-restarting register: reboot_required_file - name: Check if a reboot is required ansible.builtin.command: needs-restarting -r register: reboot_check ignore_errors: yes # Important: The command returns a non-zero exit code if a reboot is needed #changed_when: false # This command does not change the system state - name: Reboot the server if required ansible.builtin.reboot: msg: "System is going down for reboot after package updates." when: reboot_check.rc == 1 # needs-restarting -r returns 1 if a reboot is needed # - name: Reboot if required # ansible.builtin.reboot: # reboot_timeout: 120 # Adjust timeout as needed # when: reboot_required_file.stat.exists