Vagrant forward a range of ports

Is there a way to forward a range of ports using vagrant 1.2.1 or higher? I know that you can forward any number of ports individually by using

config.vm.forward_port 80, 4567

Or, is the answer simply don't use vagrant to do such a thing?


Solution 1:

If anyone needs an example of how to do the loop in your Vagrantfile here it is:

for i in 64000..65535
    config.vm.network :forwarded_port, guest: i, host: i
end

The above loop will forward all ports between 64000 and 65535 to the exact same port on the guest (note that 64000 and 65535 are inclusive).

Solution 2:

The 'for' examples above are correct for doing an inclusive range. If you would like to forward a set of specific ports, you need to use the Ruby .each operator.

The variables can go inside or outside of the main Vagrant.configure loop.

UDP_PORTS_LIST={
  "5000" => 5000, # Some service
}

TCP_PORTS_LIST={
  "5900" => 5900, # VNC
}

The loops need to go inside the Vagrant.configure block for the VM you want to map them for (remember you can have multiple VMs in a single Vagrantfile).

UDP_PORTS_LIST.each do |guest, host|
  config.vm.network "forwarded_port", guest: "#{guest}", host: "#{host}", protocol: "udp"
end
TCP_PORTS_LIST.each do |guest, host|
  config.vm.network "forwarded_port", guest: "#{guest}", host: "#{host}", protocol: "tcp"
end