We have a Vagrant set-up running Ubuntu 12.04 as the guest OS across our team where the host OS is Windows 7 or 8. What I'd like to be able to do is to is to get the hostname of the Windows host machine and append this to the Vagrant hostname during setup e.g.
config.vm.hostname = <windows hostname>-web
This is because we have several developers connecting to external services from their local dev machines and if we all have the same hostname set (as the Vagrant file is source controlled and is the same for everyone) then in the logs for these external services we can't differentiate who made what request to the service. I thought if we were able to dynamically get the hostname from the host OS it would be a good way to identify individual guest OSes running on each developers machine.
Is this possible and if so what is the best way to achieve it?
In Windows, the environment variable COMPUTERNAME holds the hostname. Since Vagrantfile is actually a Ruby script, you can set the hostname like this:
config.vm.hostname = "#{ENV['COMPUTERNAME']}-web"
On OSX ENV['COMPUTERNAME']
will evaluate to nil
so you could use this to set the hostname on any Windows/*nix system:
config.vm.hostname = "#{ENV['COMPUTERNAME'] || `hostname`[0..-2]}-web"
Update: I never realized that Windows has a hostname
command. At least Windows 7 does. I don't know how far back it goes. So you could simply use the following on all systems:
config.vm.hostname = "#{`hostname`[0..-2]}-web"
I used this technique but I had to modify the expression somewhat. If hostname returns an FQDN like it does on the Mac, the original didn't quite work.
Below is Working solution for both Mac and Windows.
config.vm.hostname = "#{`hostname`[0..-2]}".sub(/\..*$/,'')+"-web"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With