Class: VagrantPlugins::CommandDns::Action::GetIP

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-command-dns/action/get_ip.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, env) ⇒ GetIP

Returns a new instance of GetIP.



8
9
10
11
# File 'lib/vagrant-command-dns/action/get_ip.rb', line 8

def initialize(app, env)
  @app    = app
  @logger = Log4r::Logger.new('vagrant_command_dns::action::get_ip')
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/vagrant-command-dns/action/get_ip.rb', line 13

def call(env)
  if !env[:machine].config.dns.__skip
    if env[:machine].state.id != :running
      raise Errors::MachineStateError
    end

    ip = nil

    case env[:machine].provider_name
    when :virtualbox
      # We only operate on the first network defined in the Vagrantfile
      unless env[:machine].config.vm.networks[1].nil?
        network = env[:machine].config.vm.networks[1]
        if network[1][:dns] == 'skip'
          @logger.info('')
          env[:ui].info('')
        else
          cmd = "vagrant ssh -c \"ip -4 addr show \\$(ip -4 route | head -n2 | tail -n1 | awk '{print \\$5}') | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}'\" 2>/dev/null"
          begin
            ip = IPAddr.new(`#{cmd}`.chomp)
          rescue IPAddr::InvalidAddressError
            raise Errors::InvalidAddressError
          end
        end
      end

    else
      raise Errors::UnsupportedProviderError
    end

    unless ip.nil?
      host_names = [env[:machine].config.vm.hostname]
      env[:machine].config.dns.aliases.each do |a|
        host_names.push(a)
      end

      record_map = {}
      host_names.each do |h|
        env[:ui].info "#{h} #{ip.to_string}"
        record_map[h] = ip.to_string
      end

      env[:record_map] = record_map
    end

  else
    host_names = [env[:machine].config.vm.hostname]
    env[:machine].config.dns.aliases.each do |a|
      host_names.push(a)
    end

    record_map = {}
    host_names.each do |h|
      record_map[h] = ip
    end

      env[:record_map] = record_map
  end

  @app.call(env)
end