Multiple VMs at once with Vagrant and VirtualBox

, ,

In this post, I showed how to provision a Ubuntu VM using Vagrant and VirtualBox, now here is an updated version to provision as many as you want (and your hardware supports) within a single script.

Basically, the script is the same as before, the difference is that I’ve set some variables and moved the configuration part inside a loop.

# Define how many VMs you want to be provisioned
SERVERS = 3

# Specify the Network and which IP to be configured
IP_NETWORK = "10.200.200."
IP_START = 20

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/focal64"

  (1..SERVERS).each do |i|
    config.vm.define "server0#{i}" do |server|
      server.vm.network :private_network, ip: IP_NETWORK + "#{IP_START + i}", virtualbox__intnet: "redenat"
      server.vm.hostname = "server0#{i}"

      server.vm.provider :virtualbox do |vb|
        vb.customize ["modifyvm", :id, "--memory", 2048]
        vb.customize ["modifyvm", :id, "--cpus", 4]
        vb.customize ["modifyvm", :id, "--name", "server0#{i}"]
      end

      server.vm.provision "shell", inline: <<-'SHELL'
        sed -i 's/^#* *\(PermitRootLogin\)\(.*\)$/\1 yes/' /etc/ssh/sshd_config
        sed -i 's/^#* *\(PasswordAuthentication\)\(.*\)$/\1 yes/' /etc/ssh/sshd_config
        systemctl restart sshd.service
        echo -e "vagrant\nvagrant" | (passwd vagrant)
        echo -e "root\nroot" | (passwd root)
        apt-get update
      SHELL
    end
  end
end

As before, let’s run vagrant up and see the magic happens, we will have 3 pre-configured servers in less than 5 minutes.


Leave a Reply

Your email address will not be published. Required fields are marked *