diff --git a/README.md b/README.md index 315ff08..da10199 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,25 @@ At the moment, the only things you need, are the hostname and a :private_network This ip and the hostname will be used for the entry in the /etc/hosts file. +## For AWS + +If you'd like AWS as a provider using [vagrant-aws](https://github.com/mitchellh/vagrant-aws) or other plugin, +this plugin will detect the instance public IP by the tag infomations. +For example, [vagrant-aws](https://github.com/mitchellh/vagrant-aws) configures a tag infomations like the following. + + config.vm.provider :aws do |aws, override| + aws.tags = { + "Name" => "vagrant", + ... + } + aws.elastic_ip = true + ... + end + +* [AWS CLI](https://aws.amazon.com/cli/) is required +* Make the tag infomations be unique for the instance +* Enable Elastic IP for the instance + ## Versions ### 0.0.11 diff --git a/lib/vagrant-hostsupdater/HostsUpdater.rb b/lib/vagrant-hostsupdater/HostsUpdater.rb index 45ec37a..970b02f 100644 --- a/lib/vagrant-hostsupdater/HostsUpdater.rb +++ b/lib/vagrant-hostsupdater/HostsUpdater.rb @@ -1,3 +1,5 @@ +require 'open3' + module VagrantPlugins module HostsUpdater module HostsUpdater @@ -5,10 +7,14 @@ module HostsUpdater def getIps ips = [] - @machine.config.vm.networks.each do |network| - key, options = network[0], network[1] - ip = options[:ip] if key == :private_network - ips.push(ip) if ip + if ip = getAwsPublicIp + ips.push(ip) + else + @machine.config.vm.networks.each do |network| + key, options = network[0], network[1] + ip = options[:ip] if key == :private_network + ips.push(ip) if ip + end end return ips end @@ -116,6 +122,26 @@ def sudo(command) `sudo #{command}` end end + + + private + + def getAwsPublicIp + aws_conf = @machine.config.vm.get_provider_config(:aws) + return nil if ! aws_conf.is_a?(VagrantPlugins::AWS::Config) + filters = ( aws_conf.tags || [] ).map {|k,v| sprintf('"Name=tag:%s,Values=%s"', k, v) }.join(' ') + return nil if filters == '' + cmd = 'aws ec2 describe-instances --filter '+filters + stdout, stderr, stat = Open3.capture3(cmd) + @ui.error sprintf("Failed to execute '%s' : %s", cmd, stderr) if stderr != '' + return nil if stat.exitstatus != 0 + begin + return JSON.parse(stdout)["Reservations"].first()["Instances"].first()["PublicIpAddress"] + rescue => e + @ui.error sprintf("Failed to get IP from the result of '%s' : %s", cmd, e.message) + return nil + end + end end end end