Ansible reboot a Debian/Ubuntu Linux for kernel update and wait for it

Originally published at: https://www.cyberciti.biz/faq/ansible-reboot-debian-ubuntu-linux-for-kernel-update-waitforit/

How can I reboot a Debian or Ubuntu Linux server/host remotely using an Ansible playbook for kernel update and wait for it to come back again?

I got my solution from the ansible issue tracker #14413 (sorry can only add two links…) and everybody there uses async: 1. As you set poll: 0 you do not really check the return status and so async: 300 becomes irrelevant. Just do not make the mistake I made and set async: 0 which is the same as leaving it out and results in a fatal error every time. :wink:

You should also reference the issue “Proper reboot module as action plugin” and the related pull-request “[WIP] Add reboot action plugin”. I think a proper module for rebooting is important because there are so many caveats. Unfortunately the momentum for the PR seems to be lost.

One more thing I did is, split up the check for reboot requirement and actual reboot. That way I can trigger the reboot from multiple sources and it is always done at the very end.

tasks:

- name: 'Reboot if necessary'
  stat:
    path: /var/run/reboot-required
  register: result
  changed_when: result.stat.exists
  notify: 'restart server'

handlers:

- name: 'Reboot server'
  shell: 'sleep 5 && shutdown -r now "Rebooting to complete system upgrade"'
  become: yes
  async: 1
  poll: 0
  listen: 'restart server'

- name: 'Wait for host to become available again'
  wait_for_connection:
    delay: 30
    connect_timeout: 10
    sleep: 10
    timeout: 300
  listen: 'restart server'
1 Like

Thanks for posting your solution.