Reboot RHEL when Linux kernel installed with Ansible playbook

I know ansible.builtin.reboot is used to reboot remote VM Ansible reboot Linux machine or server with playbooks - nixCraft and ansible.builtin.reboot module – Reboot a machine — Ansible Documentation

- name: Unconditionally reboot the machine with all defaults
  ansible.builtin.reboot:

I only need to reboot the server when a new Linux kernel is installed. How do I tell and set conditions with Ansible to reboot the machine only when a new Linux kernel is installed by the dnf or yum module?

Use the needs-restarting command. We can quickly check if CentOS / RHEL / Fedora / Rocky / Alma and Amazon Linux needs reboot using a command-line option. See How to check if CentOS / RHEL needs a full reboot - nixCraft for more info.

Ansible playbook to reboot the RHEL/CentOS/Rocky/Alma/Amazon Linux EC2 host when the kernel update installed by the dnf/yum command.

---
- hosts: awswwwcluster
  tasks:
    - name: Update each Amazon Linux EC2 instance
      ansible.builtin.yum:
          name: '*'
          state: latest

    - name: See if an Amazon Linux instance needs a reboot
      ansible.builtin.command: needs-restarting -r
      register: reg_reboot_required
      ignore_errors: true
      failed_when: false
      changed_when: reg_reboot_required.rc != 0
      notify:
          - Reboot AmazonLinux
    
  handlers:
      - name: Reboot AmazonLinux
        ansible.builtin.reboot:
            msg: "Reboot initiated by Ansible after Linux kernel update"
            reboot_timeout: 3600
            test_command: w

That is all.

1 Like