|
| 1 | +module VagrantPlugins |
| 2 | + module HostManager |
| 3 | + module Action |
| 4 | + class UpdateHostsFile |
| 5 | + def initialize(app, env) |
| 6 | + @app, @env = app, env |
| 7 | + @translator = Helpers::Translator.new('action.update_hosts_file') |
| 8 | + @logger = |
| 9 | + Log4r::Logger.new('vagrant_hostmanager::action::update') |
| 10 | + end |
| 11 | + |
| 12 | + def call(env) |
| 13 | + global_env = env[:machine].env |
| 14 | + current_provider = env[:machine].provider_name |
| 15 | + |
| 16 | + # build a list of host entries based on active machines that |
| 17 | + # are using the same provider as the current one |
| 18 | + matching_machines = [] |
| 19 | + entries = {} |
| 20 | + entries['127.0.0.1'] = 'localhost' |
| 21 | + global_env.active_machines.each do |name, provider| |
| 22 | + if provider == current_provider |
| 23 | + machine = global_env.machine(name, provider) |
| 24 | + host = machine.config.vm.hostname || name |
| 25 | + entries[get_ip_address(machine)] = host |
| 26 | + matching_machines << machine |
| 27 | + end |
| 28 | + end |
| 29 | + |
| 30 | + # generate hosts file |
| 31 | + path = env[:tmp_path].join('hosts') |
| 32 | + File.open(path, 'w') do |file| |
| 33 | + entries.each_pair do |ip, host| |
| 34 | + @logger.info "Adding /etc/hosts entry: #{ip} #{host}" |
| 35 | + file << "#{ip}\t#{host}\n" |
| 36 | + end |
| 37 | + end |
| 38 | + |
| 39 | + # copy the hosts file to each matching machine |
| 40 | + # TODO append hostname to loopback address |
| 41 | + matching_machines.each do |machine| |
| 42 | + env[:ui].info @translator.t('update', { :name => machine.name }) |
| 43 | + machine.communicate.upload(path, '/tmp/hosts') |
| 44 | + machine.communicate.sudo("mv /tmp/hosts /etc/hosts") |
| 45 | + end |
| 46 | + |
| 47 | + @app.call(env) |
| 48 | + end |
| 49 | + |
| 50 | + protected |
| 51 | + |
| 52 | + def get_ip_address(machine) |
| 53 | + ip = nil |
| 54 | + machine.config.vm.networks.each do |network| |
| 55 | + key, options = network[0], network[1] |
| 56 | + ip = options[:ip] if key == :private_network |
| 57 | + next if ip |
| 58 | + end |
| 59 | + |
| 60 | + ip || machine.ssh_info[:host] |
| 61 | + end |
| 62 | + end |
| 63 | + end |
| 64 | + end |
| 65 | +end |
0 commit comments