--- # Reboot Ubuntu servers that have /run/reboot-required set, with a ntfy alert per server. # Order: pi-hole (DNS) first and alone, then the rest a few at a time, then this # Ansible controller last, so it never reboots out from under the run. # The hostnames for the DNS server and the controller are also in the play patterns below. - name: Find servers that need a reboot hosts: ubuntu_servers become: true gather_facts: false tasks: - name: Check for the reboot-required flag ansible.builtin.stat: path: /run/reboot-required register: reboot_required - name: Group servers that need a reboot ansible.builtin.group_by: key: needs_reboot when: reboot_required.stat.exists - name: Reboot servers hosts: needs_reboot:!ansible.ki5bhv.com become: true gather_facts: false vars: dns_server: pi-hole-server.ki5bhv.com ntfy_url: https://ntfy.ki5bhv.com/server tasks: - name: Reboot and notify block: # Runs on its own before anything else, so the other servers boot with DNS available. - name: Reboot DNS server first ansible.builtin.reboot: reboot_timeout: 1800 when: inventory_hostname == dns_server - name: Reboot remaining servers ansible.builtin.reboot: reboot_timeout: 1800 when: inventory_hostname != dns_server throttle: 1 # one at a time: parallel boots overload the Proxmox host and services time out - name: Notify reboot succeeded ansible.builtin.uri: url: "{{ ntfy_url }}" method: POST body: "{{ inventory_hostname }} needed a reboot and was rebooted" delegate_to: localhost become: false rescue: - name: Notify reboot failed ansible.builtin.uri: url: "{{ ntfy_url }}" method: POST body: "{{ inventory_hostname }} needed a reboot but it FAILED - check reboot.log" headers: Priority: high delegate_to: localhost become: false - name: Mark host as failed ansible.builtin.fail: msg: "Reboot of {{ inventory_hostname }} failed" - name: Reboot this Ansible controller last hosts: needs_reboot:&ansible.ki5bhv.com become: true gather_facts: false vars: ntfy_url: https://ntfy.ki5bhv.com/server tasks: # Sent first: once the reboot happens, nothing is left to report back. - name: Notify controller reboot ansible.builtin.uri: url: "{{ ntfy_url }}" method: POST body: "{{ inventory_hostname }} (Ansible controller) needed a reboot and is rebooting in 1 minute" delegate_to: localhost become: false # The reboot module can't wait for the machine it is running on, so schedule it # a minute out and let this run finish and write its log first. - name: Schedule reboot in 1 minute ansible.builtin.command: argv: [shutdown, -r, "+1", "Ansible - reboot required"] changed_when: true