---

# Reboot the machine gets more complicated as we want to support bastion hosts. A simple wait_for task would not work
# as we can not directly reach the hosts (except the bastion). In case a basion is used, we first check for it to come
# back. After it is back, we check for all the hosts by delegating to the bastion.

- name: Rebooting server
  shell: nohup bash -c "sleep 5 && shutdown -r now 'Reboot required for updated kernel'" &

- name: Wait for some seconds
  pause:
    seconds: 10

- set_fact:
    is_bastion: "{{ inventory_hostname == 'bastion' }}"
    wait_for_delegate: "localhost"

- set_fact:
    wait_for_delegate: "{{hostvars['bastion']['ansible_ssh_host']}}"
  when: "'bastion' in groups['all']"

- name: wait for bastion to come back
  wait_for:
    host: "{{ ansible_ssh_host }}"
    port: 22
    delay: 10
    timeout: 300
  become: false
  delegate_to: localhost
  when: is_bastion

- name: waiting for server to come back (using bastion if necessary)
  wait_for:
    host: "{{ ansible_ssh_host }}"
    port: 22
    delay: 10
    timeout: 300
  become: false
  delegate_to: "{{ wait_for_delegate }}"
  when: not is_bastion
