Search code examples
ubuntuvagrantvirtualbox

Vagrant with Virtualbox does not start because of standard DHCP "vboxnet0" on ubuntu


On vagrant up vagrant shows an error starting with:

A host only network interface you're attempting to configure via DHCP already has a conflicting host only adapter with DHCP enabled. [...]

This is with a fresh install and a known issue since 2014. The workaround is to execute VBoxManage dhcpserver remove --netname HostInterfaceNetworking-vboxnet0 manually every time before vagrant up.

But how can this be done automatically?


Solution

  • Putting the following code at the beginning of your Vagrantfile will solve the issue automatically and only execute on linux based os:

    Vagrant.configure("2") do |config|
          
          host = RbConfig::CONFIG['host_os']
          if host =~ /(linux)/
            config.trigger.before :up do |trigger|
                trigger.warn = "removing standard dhcp host interface if existent"
                trigger.run = {inline: "bash -c 'if [ $( VBoxManage list dhcpservers | grep -c vboxnet0 ) != \"0\" ]; then VBoxManage dhcpserver remove --netname HostInterfaceNetworking-vboxnet0; fi'"}
              end
          end
    
    # [...] your other code here ---
    
    end
    

    The code checks if there is a dhcp server whichs name includes the string vboxnet0 first because otherwise VBoxManage would end with an error preventing you from starting up the virtual machine should the standard dhcp not exist (which happens sometimes).