awendt
awendt

Reputation: 13723

Can I programmatically access Vagrant's auto-corrected port forwarding?

I hard-coded a port forwarding in my Vagrantfile and now it collides with another box running on my machine.

I am aware Vagrant can detect port collisions and correct them. But one of the recipes I'm running depends on knowing the port for some other configuration.

Can I programmatically find out which port Vagrant detected as not in use so the recipe can make use of it?

Upvotes: 2

Views: 244

Answers (2)

conorsch
conorsch

Reputation: 1496

Install the vagrant-portinfo plugin:

$ vagrant plugin install vagrant-portinfo`
$ vagrant portinfo
server1 (84a1587) running
------------------------------------------------
guest: 22       host: 2201
guest: 8080     host: 8083

You'll have to do a bit of grepping to parse the output. Adding programmatic querying of forwarded ports has been on the roadmap in Vagrant for years now, and there's still an open issue discussing it.

Upvotes: 1

thomaswsdyer
thomaswsdyer

Reputation: 356

There's no built-in command for this, but if you're using VirtualBox as your provider you can get port information using:

$ VBoxManage showvminfo $(cat .vagrant/machines/default/virtualbox/id) --details --machinereadable | egrep Forwarding

Giving you an output similar to:

Forwarding(0)="ssh,tcp,127.0.0.1,2222,,22"
Forwarding(1)="tcp8080,tcp,,8080,,80"

In the above, port 22 of the VM is forwarded to 2222 of the host, and 80 to 8080.

The VMNAME can be found by using vagrant's global-status command:

$ vagrant global-status
id       name    provider   state   directory
------------------------------------------------------------------------
78cf051  default virtualbox running /path/to/Vagrantfile

In the example above, default is the VMNAME.

Upvotes: 1

Related Questions