21

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?

Acorn
  • 313
  • 1
  • 2
  • 6
  • Does this help? http://docs.vagrantup.com/v2/networking/forwarded_ports.html – dawud Jun 29 '13 at 10:44
  • Not exactly. Wanted to know if you can specify a range of ports to be open, rather than one at a time. Perhaps I'll contact the author directly. – Acorn Jun 30 '13 at 12:19
  • 5
    Since the Vagrantfile is just a Ruby script you might be able to write a for loop that executes config.vm.forward_port for every port you want. I'm not fluent in Ruby, so I can't really help you with code. – Lasar Jul 08 '13 at 12:27

2 Answers2

30

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).

ddelrio1986
  • 416
  • 5
  • 5
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
dragon788
  • 756
  • 6
  • 10