Managing windows hosts with ansible

Lately I’ve been experimenting with ansible a lot.

Dealing with linux hosts is straightforward enough, and you’ll be able to find all sorts of information with google, but ansible can also deal with windows hosts, and that’s where it gets a bit more interesting.

To be able to manage a windows host with ansible, you have to:

  • create a user account on the machine (or in the windows domain) who has to be a member of the administrators group
  • follow the instructions in the ansible documentation about how to enable winrm
  • make sure you use the right ansible modules, if there are special modules for windows for any given purpose they will start with win_, for example instead of copy: for a windows host you’d use win_copy. Some modules simply do not exist as a win_ version, but the generic unix version does not work on windows, for example the telegram notification module, but that you can safely delegate_to: localhost when you want to use it (unless your management host does not have internet access).
  • set up a group in your inventory for your windows hosts, and add the variables for winrm access as group_vars for that group

Here’s an example for a simple playbook that installs all the latest updates, and reboots the target host if necessary:

---
- name: Install all windows updates
  hosts: all

  tasks:

  - name: install all updates
    win_updates:
      category_names:
        - SecurityUpdates
        - CriticalUpdates
        - UpdateRollups
      state: installed
    register: update_result
    notify:
      - telegram-notify
      - reboot-if-required

  handlers:

  - name: telegram-notify
    telegram:
      msg: "{{ ansible_fqdn }}: updates installed."
      token: "{{ eregion_home_telegram_token }}"
      chat_id: "{{ eregion_home_telegram_chat_id }}"
    delegate_to: localhost

  - name: reboot-if-required
    win_reboot:
    when: update_result.reboot_required and not eregion_home_has_dualboot

You’ll notice that the handler: that reboots the target has a when: condition that uses a variable I haven’t mentioned yet. It’s easy enough: two of the windows hosts I am managing have dual boot setups, by default they reboot to linux. I’m dealing with that by creating TWO host entries in my inventory, the regular one, and one with a different name, and two host_vars:

lemmy@kumiko:~/.ansible/inventory> tail -6 51-hosts
[windows]
kumiko-win
kirika-win
yuzuyu.eregion.home

and

lemmy@kumiko:~/.ansible/inventory> cat host_vars/kumiko-win.yml 
---
ansible_host: kumiko.eregion.home

This works with ansible on the command line and with ansible tower.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: