ThorneLabs

Multi-machine Vagrantfile with Shorter, Cleaner Syntax Using JSON and Loops


In a previous post, I provided an example Vagrantfile to create multiple virtual machines. That Vagrantfile works perfectly fine, but it contains a lot of redundant code. Because a Vagrantfile is written in Ruby, it is possible to create a Vagrantfile with shorter, cleaner syntax using JSON and loops.

The following Vagrantfile uses JSON to define the unique parameters (name, mem, cpu, etc.) for each virtual machine. Then, a for each loop will iterate through the JSON to input the necessary values in the virtual machine definition that now only needs to be defined once instead of three times.

Example Vagrantfile

# -*- mode: ruby -*-

# vi: set ft=ruby :

boxes = [
    {
        :name => "server1",
        :eth1 => "192.168.205.10",
        :mem => "1024",
        :cpu => "1"
    },
    {
        :name => "server2",
        :eth1 => "192.168.205.11",
        :mem => "1024",
        :cpu => "2"
    },
    {
        :name => "server3",
        :eth1 => "192.168.205.12",
        :mem => "2048",
        :cpu => "2"
    }
]

Vagrant.configure(2) do |config|

  config.vm.box = "base"

  config.vm.provider "vmware_fusion" do |v, override|
    override.vm.box = "base"
  end

  # Turn off shared folders
  config.vm.synced_folder ".", "/vagrant", id: "vagrant-root", disabled: true

  boxes.each do |opts|
    config.vm.define opts[:name] do |config|
      config.vm.hostname = opts[:name]

      config.vm.provider "vmware_fusion" do |v|
        v.vmx["memsize"] = opts[:mem]
        v.vmx["numvcpus"] = opts[:cpu]
      end

      config.vm.provider "virtualbox" do |v|
        v.customize ["modifyvm", :id, "--memory", opts[:mem]]
        v.customize ["modifyvm", :id, "--cpus", opts[:cpu]]
      end

      config.vm.network :private_network, ip: opts[:eth1]
    end
  end
end

References

If you found this post useful and would like to help support this site - and get something for yourself - sign up for any of the services listed below through the provided affiliate links. I will receive a referral payment from any of the services you sign-up for.

Get faster shipping and more with Amazon Prime: About to order something from Amazon but want to get more value out of the money you would normally pay for shipping? Sign-up for a free 30-day trial of Amazon Prime to get free two-day shipping, access to thousands of movies and TV shows, and more.

Thanks for reading and take care.