Adding Hyper-V to Windows 11 Pro with Ansible
VirtualBox (my preferred desktop virtualisation tool) and Hyper-V conflict, but Hyper-V is required for some software and features to work correctly on Windows 11. In particular the wonderful Windows Subsystem for Linux (WSL) version 2 (and I specifically mean “WSL2” is wonderful, the original WSL wasn’t great) uses a Hyper-V VM. Following on from my post on managing Windows with Ansible and customising the taskbar and startup programs with Ansible, I will be Ansibleising installing Hyper-V (and as such, this will be a short post - Ansible makes things like this really easy).
The Ansible module to install features on client versions of Windows (e.g. Windows 10, Windows 11 etc.) is win_optional_feature
. For servers it’s win_feature. No, I don’t know why Microsoft made it entirely different either. To see the available features (again this is for client versions, there’s different commands for server versions) the powershell command is Get-WindowsOptionalFeature -Online
. They can be installed and removed with Enable-WindowsOptionalFeature -FeatureName <name> -Online
and Disable-WindowsOptionalFeature -FeatureName <name> -Online
.
My entire Ansible task file for installing Hyper-V is:
---
- name: Install Hyper-V (full)
ansible.windows.win_optional_feature:
# This should also install:
# Microsoft-Hyper-V
# Microsoft-Hyper-V-Tools-All
# Microsoft-Hyper-V-Management-Powershell
# Microsoft-Hyper-V-Hypervisor
# Microsoft-Hyper-V-Services
# Microsoft-Hyper-V-Management-Clients
name: Microsoft-Hyper-V-All
state: present
register: hyper_v_install
- name: Check if reboot required and notify handlers
ansible.builtin.debug: msg="Reboot is{% if not hyper_v_install.reboot_required %} not{% endif %} required"
changed_when: hyper_v_install.reboot_required
notify: Reboot Windows desktop
...
The user of the ansible.builtin.debug
module to notify the reboot handler is a bit of a kludge, but it is necessary to test if reboot_required
is set in the return code to decide if it is necessary. Rather than just reboot, I put the reboot as a handler so that I will be able to signal it from other places where a reboot is needed but only do the reboot once.
The handlers file looks like this:
---
- name: Reboot Windows desktop
ansible.windows.win_reboot:
pre_reboot_delay: 10
...
This does notify the logged in user with the default message (“Reboot initiated by Ansible”) but there is no indication of when the reboot will occur - I would have preferred it display a countdown or progress bar to the reboot.
Originally, I set the delay to 60 seconds (thinking I would get such a countdown) but when I discovered there’s no feedback on how long is left until the reboot I instead changed it to a much shorter delay (10 seconds) between the message and actual reboot.