top of page
Writer's pictureSiddhesh Kadam

Ansible to Automate Server Reboot a Linux server

You can use Ansible to Automate Server Reboot a Linux server and wait for it to come back online. Here's a simple playbook to understand Server Reboots with Ansible.

---
- name: Restart Linux Server and Wait For Connection
  hosts: web1
  gather_facts: no  
  become: yes
  tasks:
    - name: Reboot the web1 server
      command: reboot
      async: 1
      poll: 0
      ignore_errors: yes
      changed_when: false
    - name: Wait for the server to respond back
      wait_for_connection:
        timeout: 300  

Make sure to replace web1 with the target server's hostname or IP address in your inventory file. You can also adjust the timeout value in the "Wait for the server to come back online" task to match your server's reboot time, as the required waiting time may vary depending on your system.


Here's a breakdown of what the playbook does:


hosts: Specifies the target server where you want to reboot.


gather_facts: We set it to "no" to skip gathering facts about the server since we don't need them in this playbook.


The playbook consists of two tasks:


The first task runs the reboot command on the target server with async and poll parameters. The async parameter makes the task asynchronous, and the poll parameter is set to 0, meaning Ansible will not wait for the command to finish. We also set ignore_errors to "yes" to prevent Ansible from considering this task as failed if the server disconnects during the reboot. We use changed_when: false to ensure Ansible reports the task as unchanged because the reboot command will disconnect Ansible.


The second task uses the wait_for_connection module to wait for the target server to come back online. It waits for a specified amount of time (in this example, 300 seconds) for the server to be reachable again.


Please ensure you have SSH access to your server and the necessary Ansible configuration set-up before running this playbook. Additionally, consider the potential downtime and data loss when rebooting a server, and make sure this is performed during a maintenance window.








bottom of page