Ansible is developing quickly and the older answers were not working for me.
I found two issues:
- The recommended way of rebooting may kill the SSH connection before Ansible finishes the task.
It is better to run: nohup bash -c "sleep 2s && shutdown -r now" &
This will launch a shell with the sleep
&& shutdown
, but will not wait for the shell to end due to the last &
. The sleep will give some time for the Ansible task to end before the reboot and the nohup
will guarantee that bash doesn't get killed when the task ends.
- The
wait_for
module is not reliably waiting for the SSH service.
It detects the port open, probably open by systemd, but when the next task is run, SSH is still not ready.
If you're using Ansible 2.3+, wait_for_connection works reliably.
The best 'reboot and wait' in my experience (I am using Ansible 2.4) is the following:
- name: Reboot the machine
shell: nohup bash -c "sleep 2s && shutdown -r now" &
- name: Wait for machine to come back
wait_for_connection:
timeout: 240
delay: 20
I've got the nohup command from: https://github.com/keithchambers/microservices-playground/blob/master/playbooks/upgrade-packages.yml
I edited this message to:
- add krad's portability suggestion, using shutdown -r now instead of reboot
- add a delay. It is needed to avoid Ansible to execute the next step if the reboot is slow
- increase the timeout, 120s was too little for some slow BIOS.