In The Internet Pale

Automatically Select Box For Provider in Vagrant

Vagrant is an indispensable tool which allows us to easily run and work on different projects without spending much time setting up developer machines.

People in our team have already invested in different virtual machines. Some of us got VMware and some Parallels. We wanted to provide seamless experience for everybody without a need to customize Vagrantfile for your own environment.

Vagrant 1.5 solves this by introducing generic names for boxes (like chef/centos-6.5) as well as centralized hosting. Each name can represent not one but a set of boxes for different VMs. Vagrant will try to download concrete box for used VM provider when you run vagrant up.

Unfortunately there is no box set which includes images for all VMs we use. Which leads us to another option: it’s possible to override global vagrant settings from provider’s config. For this purpose provider’s config block receives second arguments:

config.vm.provider :virtualbox do |vb, override|
  override.vm.box = "chef/centos-6.5"
end

Full Example of Our Base Config

# This config uses new syntax for box names which was introduced in vagrant 1.5
Vagrant.require_version ">= 1.5"

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # Every Vagrant virtual environment requires a box to build off of.
  # Our developers use different virtual machines to work (which can produce
  # bugs which are hard to reproduce but let's leave it for now) so we moved
  # box definition into configuration of specific provider.
  # When user runs `vagrant up` it will pick up correct box
  # from provider specific config.
  #
  # It is implemented with override object which is documented
  # here https://docs.vagrantup.com/v2/providers/configuration.html

  config.vm.provider :vmware_fusion do |wmf, override|
    override.vm.box = "chef/centos-6.5"
  end

  config.vm.provider :parallels do |v, override|
    override.vm.box = "parallels/centos-6.5"
  end

  config.vm.provider :virtualbox do |vb, override|
    override.vm.box = "chef/centos-6.5"
  end
end