--- - name: Update and upgrade Ubuntu servers hosts: ubuntu_servers become: yes tasks: # Wait for apt/dpkg to be free (avoid lock errors) - name: Ensure no apt/dpkg process is running ansible.builtin.shell: | pids=$(pgrep -x apt-get || true) if [ -n "$pids" ]; then echo "apt-get running: $pids"; exit 1; fi pids=$(pgrep -x dpkg || true) if [ -n "$pids" ]; then echo "dpkg running: $pids"; exit 1; fi register: check_apt changed_when: false failed_when: false retries: 10 delay: 15 until: check_apt.rc == 0 # Repair any half-configured packages before proceeding - name: Repair any broken or half-configured packages ansible.builtin.shell: | dpkg --configure -a || true apt-get -f install -y || true changed_when: false - name: Update apt package index ansible.builtin.apt: update_cache: yes - name: Upgrade all installed packages to latest version ansible.builtin.apt: upgrade: full # your choice; 'full' == 'dist' autoremove: yes autoclean: yes force_apt_get: yes register: upgrade_result retries: 5 delay: 30 until: upgrade_result is succeeded - name: Check if a reboot is required ansible.builtin.stat: path: /var/run/reboot-required register: reboot_check - name: Reboot if required ansible.builtin.reboot: reboot_timeout: 1200 when: reboot_check.stat.exists