Making vagrant-hostmanager UAC prompts go away on Windows

March 3, 2021 

The vagrant-hostmanager plugin is a really nice plugin which helps Vagrant VMs communicate with each other using names instead of IP addresses. Essentially it manages hosts entries for the VMs, acting like a poor-man's DNS. Now, on *NIX operating systems you typically use sudo, which caches your authorization. So, when hostmanager starts, you type your password once and then it is able to add all the host entries it needs to /etc/hosts. This is not so on Windows: you will get one UAC prompt per modification to c:\windows\system32\drivers\etc\hosts. This will eventually drive you crazy. To fix this you need to permit your Windows user account to modify the hosts-file without privilege elevation. To pull this off, you will need to modify that file's access control lists. The process is quite convoluted imho, but here it goes:

# Allow current user to write c:\windows\system32\drivers\etc\hosts
# without a prompt. This is very useful with vagrant-hostmanager. Use
# with your own risk.

$hostsfile = "c:\windows\system32\drivers\etc\hosts"

# Get current ACLs
$acl = Get-Acl $hostsfile

# Craft a new Access rule
$accessrule = New-Object System.Security.AccessControl.FileSystemAccessRule("${env:UserDomain}\${env:UserName}", "FullControl", "Allow")

# Set access rules
$acl|Set-Acl $hostsfile

So basically we take the current ACLs into an object, add an access rule and apply the object back. Based on my earlier and current research this approach seems to be the de facto standard in Powershell ACL management. There may be corner cases where this recipe fails, but "it did work on my computer".

Note that you want to get the initial ACL object from the file you're going to modify: otherwise you could mess up its ACLs badly.

Samuli Seppänen
Samuli Seppänen
Author archive