I am currently working with Vagrant for the first time, and therefore also working with Ruby for the first time. I have a specific hostname and IP address I would like set for my VM, both of which are stored in my hosts file. I would like to define the hostname in my Vagrantfile, and then have it automatically pull the matching IP address out of my hosts file for me. To do so, I have written the following code in my Vagrantfile:
Vagrant.configure("2") do |config|
hostname = "vagrantvm"
hostfile = "/etc/hosts"
ip_address = File.foreach(hostfile).grep(/\b#{hostname}\b/) { |m| /^([0-9\.]*)\b.*/.match(m)[1] }.first
config.vm.network :private_network, :ip => ip_address
config.vm.hostname = hostname
config.vm.provision :shell, :path => "bootstrap.sh"
end
Line 5 where I am assigning ip_address
works, however I am not sure if it is the right way to do it. It seems a little ugly and long. I was thinking that maybe I should not put the code block passed to grep
all on the same line. Or is it even necessary to have 2 separate regexes in there? Can it be done in 1 step?
It also seems strange to me that I need to add .first
on the end in order to get the IP address string out of the array returned by grep
. I feel like there is a better way to do this that I am missing.