ansible,

Reboot VMs with Ansible

Sep 14, 2021 · 2 mins read · Post a comment

Speaking of configuration management, Ansible is the most popular open-source automation tool out there. It’s mostly used for automating day to day operation activities, from installing security patches to deploying applications. In today’s blog post we are going to learn how can we reboot a bunch of Linux and Windows VMs (nodes).

Prerequisites

  • Ansible

Linux VMs

The bare minimum example we are going to get from the reboot module is the following:

- name: Reboot the machine with all defaults
  reboot:

Step 1. Let’s write a simple playbook named reboot.yml, that will upgrade all packages and reboot the machines.

---
- hosts: all
  become: yes

  tasks:
  - name: Upgrade packages
    yum:
      name: "*"
      state: latest
    register: upgrade_packages

  - name: Reboot machines
    reboot:
      reboot_timeout: 3600
      test_command: uptime
    when: upgrade_packages is changed

Note(s): test_command parameter will execute a command on the rebooted machine in order to check if the node state is up and running, so it could continue with the remaining tasks, if any.

Step 2. Test the playbook by running the following command:

ansible-playbook -i inventory reboot.yml

If you experience any errors, let me know in the comments below.

Windows VMs

To be honest, Windows nodes are rare to find these days as part of an Ansible inventory. I guess Microsoft got a better alternative solution with the PowerShell Desired State Configuration (DSC).

Step 1. Anyway, the Ansible module is called win_reboot, so create a reboot.yml playbook.

---
- hosts: all
  become: yes

  tasks:
  - name: Install security updates only
    win_updates:
      category_name:
      - SecurityUpdates
    register: install_upgrades

  - name: Reboot machines
    win_reboot:
      reboot_timeout: 3600
      test_command: Get-Uptime -Since
    when: install_upgrades is changed

Step 1 (Alternative). win_updates module supports reboot, so you can do the same without the win_reboot task.

---
- hosts: all
  become: yes

  tasks:
  - name: Install security updates only
    win_updates:
      category_name:
      - SecurityUpdates
      reboot: yes
      reboot_timeout: 3600

Step 2. Save and run the playbook.

ansible-playbook -i inventory reboot.yml

Conclusion

Implementing a pre-reboot and post-reboot verification tasks are important as well, especially if you don’t want to get calls from the boss on Friday evening, or Sunday morning. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.