From d0cbe7b33a87326352f59ffb9db3159c48e9a657 Mon Sep 17 00:00:00 2001 From: maximerety Date: Sun, 7 Feb 2016 15:02:52 +0100 Subject: [PATCH] Added support for multiple private_network adapters --- README.md | 21 ++++++++++++++ lib/vagrant-hostsupdater/HostsUpdater.rb | 35 +++++++++++++++++++----- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c4ae464..a75d4ca 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,27 @@ You currently only need the `hostname` and a `:private_network` network with a f This IP address and the hostname will be used for the entry in the `/etc/hosts` file. +### Multiple private network adapters + +If you have multiple network adapters i.e.: + + config.vm.network :private_network, ip: "10.0.0.1" + config.vm.network :private_network, ip: "10.0.0.2" + +you can specify which hostnames are bound to which IP by passing a hash mapping the IP of the network to an array of hostnames to create, e.g.: + + config.hostsupdater.aliases = { + '10.0.0.1' => ['foo.com', 'bar.com'], + '10.0.0.2' => ['baz.com', 'bat.com'] + } + +This will produce `/etc/hosts` entries like so: + + 10.0.0.1 foo.com + 10.0.0.1 bar.com + 10.0.0.2 baz.com + 10.0.0.2 bat.com + ### Skipping hostupdater To skip adding some entries to the /etc/hosts file add `hostsupdater: "skip"` option to network configuration: diff --git a/lib/vagrant-hostsupdater/HostsUpdater.rb b/lib/vagrant-hostsupdater/HostsUpdater.rb index 4a891cb..be7b03d 100644 --- a/lib/vagrant-hostsupdater/HostsUpdater.rb +++ b/lib/vagrant-hostsupdater/HostsUpdater.rb @@ -16,24 +16,45 @@ def getIps return ips end - def getHostnames - hostnames = Array(@machine.config.vm.hostname) - if @machine.config.hostsupdater.aliases - hostnames.concat(@machine.config.hostsupdater.aliases) + # Get a hash of hostnames indexed by ip, e.g. { 'ip1': ['host1'], 'ip2': ['host2', 'host3'] } + def getHostnames(ips) + hostnames = Hash.new { |h, k| h[k] = [] } + + case @machine.config.hostsupdater.aliases + when Array + # simple list of aliases to link to all ips + ips.each do |ip| + hostnames[ip] += @machine.config.hostsupdater.aliases + end + when Hash + # complex definition of aliases for various ips + @machine.config.hostsupdater.aliases.each do |ip, hosts| + hostnames[ip] += Array(hosts) + end end + + # handle default hostname(s) if not already specified in the aliases + Array(@machine.config.vm.hostname).each do |host| + if hostnames.none? { |k, v| v.include?(host) } + ips.each do |ip| + hostnames[ip].unshift host + end + end + end + return hostnames end - def addHostEntries() + def addHostEntries ips = getIps - hostnames = getHostnames + hostnames = getHostnames(ips) file = File.open(@@hosts_path, "rb") hostsContents = file.read uuid = @machine.id name = @machine.name entries = [] ips.each do |ip| - hostnames.each do |hostname| + hostnames[ip].each do |hostname| entryPattern = hostEntryPattern(ip, hostname) if hostsContents.match(/#{entryPattern}/)