How to reboot CentOS 7 with Ansible?

前端 未结 11 1541
遥遥无期
遥遥无期 2020-12-24 07:46

I\'m trying to reboot server running CentOS 7 on VirtualBox. I use this task:

- name: Restart server
  command: /sbin/reboot
  async: 0
  poll:          


        
11条回答
  •  攒了一身酷
    2020-12-24 08:02

    None of the above solutions worked reliably for me.

    Issuing a /sbin/reboot crashes the play (the SSH connection is closed before ansible finished the task, it crashes even with ignore_errors: true) and /usr/bin/systemd-run --on-active=2 /usr/bin/systemctl reboot will not reboot after 2 seconds, but after a random amount of time between 20 seconds and one minute, so the delay is sometime not sufficient and this is not predictable.

    Also I don't want to wait for minutes while a cloud server can reboot in few seconds.

    So here is my solution:

    - name: Reboot the server for kernel update
      shell: ( sleep 3 && /sbin/reboot & )
      async: 0
      poll: 0 
    
    - name: Wait for the server to reboot
      local_action: wait_for host="{{ansible_host}}" delay=15 state=started port="{{ansible_port}}" connect_timeout=10 timeout=180
    

    That's the shell: ( sleep 3 && /sbin/reboot & ) line that does the trick.

    Using ( command & ) in shell script runs a program in the background and detaches it: the command succeed immediately but persists after the shell is destroyed.

    Ansible get its response immediately and the server reboots 3 seconds later.

提交回复
热议问题