Last active
January 6, 2020 10:55
-
-
Save migrs/cc9107f68ac339622f03366771a682a5 to your computer and use it in GitHub Desktop.
ec2 のインスタンス名をホストファイルに登録する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'json' | |
require "optparse" | |
options = { update: true } | |
argv = [] | |
OptionParser.new do |opt| | |
opt.on("--dry-run") { |v| options[:update] = false } | |
argv = opt.parse!(ARGV) | |
end | |
def update_ec2_hosts account, options | |
res = `aws ec2 describe-instances --filters Name=instance-state-name,Values=running` | |
return if JSON.parse(res)['Reservations'].empty? | |
instances = JSON.parse(res)['Reservations'].map{ |r| r['Instances'][0] } | |
str_begin = "### #{account} BEGIN" | |
str_end = "### #{account} END" | |
hosts = instances.select {|i| | |
i.has_key?('Tags') and i.has_key?('State') and i['State']['Name'] == 'running' and i['Tags'].select { |t| t['Key'] == 'Name' }.size === 1 | |
}.map {|i| | |
name = i['Tags'].select { |t| t['Key'] == 'Name' }.first['Value'] | |
"#{i['PublicIpAddress']}\t#{account}.#{name}" | |
} | |
puts hosts | |
return unless options[:update] | |
`sed -i.bak -e "/#{str_begin}/,/#{str_end}/d" /etc/hosts` | |
open('/etc/hosts', 'a') do |f| | |
f.puts str_begin | |
f.puts hosts | |
f.puts str_end | |
end | |
end | |
account = argv.first || 'ec2' | |
update_ec2_hosts account, options |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment