Skip to content

Instantly share code, notes, and snippets.

@migrs
Last active Jan 6, 2020
Embed
What would you like to do?
ec2 のインスタンス名をホストファイルに登録する
#!/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