Search code examples
vagrantvagrantfilevagrant-provision

Vagrant: Best method for Multiple Identical VMs


I would like to provision multiple VMs with Vagrant. I would like to be able to increase the number of VMs quickly and easily.

Based on my current understanding of Vagrant. The following method detailed here https://www.edureka.co/blog/10-steps-to-create-multiple-vms-using-vagrant/ seems to be the best way:

# This defines the version of vagrant
Vagrant.configure(2) do |config|
    # Specifying the box we wish to use
    config.vm.box = "chef/centos-6.5"
    # Adding Bridged Network Adapter
    config.vm.network "public_network"
    # Iterating the loop for three times
    (1..3).each do |i|
        # Defining VM properties
        config.vm.define "edureka_vm#{i}" do |node|
            # Specifying the provider as VirtualBox and naming the VM's
            config.vm.provider "virtualbox" do |node|
                # The VM will be named as edureka_vm{i}
                node.name = "edureka_vm#{i}"  
            end
        end
    end
end

So if I want to increase from 3 to 4, I just change the loop range.

Is there another method? When I was reading the docs I was hoping there would be some version of the vagrant up command that would spin up a new unique instance.


Solution

  • Environment Variables of Vagrant is your best bet. Define something like this in your Vagrantfile.

    myVMs = ENV['NODES'] || 1

    Where NODES is an environment variable. You can use this in the following way.

    NODES=4 vagrant up

    This will update the myVMs variable in your Vagrantfile and spawn 4 VMs. You do not need to open your Vagrantfile and update it. But note, this will be for this session alone.If you want to save the value of the NODES, then you might have to add it to your ~/.profile in Linux or environment variables in windows.

    Hope this helps.