Execute a required reboot, with Ansible

Datetime:2016-08-23 03:29:19          Topic:          Share

First of all, you must ensure that this task runs last in your playbook. Else subsequent tasks will not be executed. But you also must ensure that Ansible can finish the current task, and that the reboot is not killing the network connection while the play is still running. And finally it would be nice to get feedback if the host comes up again.

The first item is easy to handle, just make the reboot task the last one in your playbook. The second one, making sure that the task can finish, can be handled by delaying the reboot.

Unfortunately the "shutdown" command in Linux can only handle delays in minute steps - and we don't want to wait a minute for the reboot. On the other hand, the Ansible task must finish. Therefore, send the entire task into the background:

( /bin/sleep 5 ; shutdown -r now "Ansible updates triggered" ) &

This will wait 5 seconds, and then immediately reboot the host. The outer brackets will make sure that the entire task is sent to the background, using the &. The full play:

# make this the last play, it might reboot the server
- hosts: all
  become: yes
  tasks:
    - name: Reboot required
      shell: ( /bin/sleep 5 ; shutdown -r now "Ansible updates triggered" ) &
            removes=/var/run/reboot-required
      async: 30
      poll: 0
      ignore_errors: true
      notify:
        - waiting for server to come back

This play starts a handler, which will wait a few seconds (to make sure the reboot is in progress) and then wait for the host to come back online:

handlers:
    - name: waiting for server to come back
      local_action: wait_for host={{ inventory_hostname }} port=22 state=started delay=10 timeout=60
      become: no