Skip to content

Commit

Permalink
Merge pull request #96 from maximerety/multiple-network-adapters
Browse files Browse the repository at this point in the history
Added support for multiple private_network adapters
  • Loading branch information
cgsmith authored Aug 11, 2016
2 parents 32ce422 + d0cbe7b commit 478ade2
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
35 changes: 28 additions & 7 deletions lib/vagrant-hostsupdater/HostsUpdater.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}/)
Expand Down

0 comments on commit 478ade2

Please sign in to comment.