Vagrant: Create a series of VMs from a hostname array
I couldn’t find any examples of creating VMs from a array of strings online so sat down to work something out myself. Here’s how you do it…
Vagrant.configure("2") do |config|
[ "web1",
"db1",
"web2",
"db2",
"backup1",
"backup2",
"admin1" ].each do |host|
config.vm.define "#{host}" do |nrpe|
nrpe.vm.box = "bento/centos-7.5"
nrpe.vm.provider :virtualbox do |vb|
vb.customize [
"modifyvm", :id,
"--name", "#{host}",
"--memory", "1024"
]
vb.cpus = 2
end
config.vm.hostname = "#{host}"
config.vm.provision :ansible do |ansible|
ansible.playbook = "basic.yml"
end
end
end
end
This Vagrantfile will create a VM for each hostname in the array as well as running the basic.yml Ansible playbook against it. You can fire it up with…
vagrant up
Once booted you can view the status of the created vms…
vagrant status
Current machine states:
web1 running (virtualbox)
db1 running (virtualbox)
web2 running (virtualbox)
db2 running (virtualbox)
backup1 running (virtualbox)
backup2 running (virtualbox)
admin1 running (virtualbox)