I'm trying to launch 2 boxes from one vagrant file using a loop. It's working, but until I try to add a port forwarding to it. I never was programming using Ruby before and I'm not super advanced using vagrant, so probably it's something simple and obvious, but I can't understand what it is.
Here is simplified example:
{
:hostname => "first",
:ip => "192.168.100.10",
:box => "minimal/xenial64",
:ram => 1024,
:cpu => 2,
:port => 9080
},
{
:hostname => "second",
:ip => "192.168.100.11",
:box => "minimal/xenial64",
:ram => 2024,
:cpu => 1,
:port => 9081
}
]
Vagrant.configure(2) do |config|
machines.each do |machine|
config.vm.define machine[:hostname] do |node|
# This is working just fine, each machine gats it's own ip, port, ram, memory
# as they specified in machines array above
node.vm.box = machine[:box]
node.vm.hostname = machine[:hostname]
node.vm.network "private_network", ip: machine[:ip]
node.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", machine[:ram]]
end
# But this is not working the same way for some reason,
# firs machine gets both ports
config.vm.network :forwarded_port, guest: 80, host: machine[:port]
#==> first: Forwarding ports...
# first: 80 (guest) => 9080 (host) (adapter 1)
# first: 80 (guest) => 9081 (host) (adapter 1)
# And than second machine obviously can start because of:
# The forwarded port to 9080 is already in use on the host machine.
end
end
end
As I suspect it was something simple and obvious, I used
config.vm.network :forwarded_port, guest: 80, host: machine[:port]
but instead
node.vm.network :forwarded_port, guest: 80, host: machine[:port]
should be used, because node
is referring to current closure.