Vagrant is a great tool for quickly spinning new environments. First time I’ve used Vagrant was when I was learning Ansible and needed something, which would help me quickly create new Virtual Machines with some basic config. The best mix is Vagrant paired with VirtualBox, that combo really works great and from my experience it’s a way to go. Unfortunately when You need WSL2 or Docker Desktop things get really complicated. VirtualBox VMs are getting really slow, sometimes they don’t even boot or You are just simple blocked from create any. I know that new version of VirtualBox tends to fix that and there are some older version, which could still work fine but from my experience it’s a constant struggle. That’s when Hyper-V comes throughout the shadows. It’s not as great as VirtualBox when paired with Vagrant but it can do the job even with it’s limitation. Below I’ll share my experience with Vagrant and Hyper-V and will show You how I’ve managed to bypass some of it’s limitation for my own purposes.

My biggest issue when working with Vagrant and Hyper-V was the inability to specify static IP addresses for my Virtual Machines(https://www.vagrantup.com/docs/providers/hyperv/limitations), which I needed for my Ansible hosts file. Also to create Virtual Machines with Vagrant You need to have a Virtual Switch in place, which wasn’t needed with VirtualBox. Based on those two things:

1) need for a Virtual Switch

2) inability to set static IPs

I’ve created a PowerShell script, which would cover those. Since I need PowerShell to deploy Virtual Switch and after that run “vagrant up” command I wanted to pass all the configuration details from PowerShell straight to Vagrantfile:

Thanks to that I can specify Virtual Machine spec without the need to change Vagrantfile. Also VMs are being created in loop, so I can create multiple VMs – both Linux and Windows:

As for networking first step is to create External switch if it doesn’t exist. The name of the switch is passed to Vagrant file so VMs can use it when created. Since static IPs can’t be created with Vagrantfile I needed to find other way to do that. For that reason I’ve created two scripts (PowerShell & bash) responsible for changing IP inside of the VM. Script are being invoked during VM provisioning and create a background job which first wait 90 seconds and after that time changes IP. Those 90 seconds and necessary for Vagrant to finish provisioning VM, if those 90 seconds are not specified Vagrant will hang on provisioning step since Virtual Machine IP was changed and it can no longer communicate with VM:

To run background job on Windows I’ve used scheduled task, which is configured to run in 90 seconds from current time:

Thanks to above solution I was able to create new Virtual Machines (both Linux and Windows) with specific IP addresses, based on the staring IP specified on main PowerShell script.

Author

Leave a Reply

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