Skip to content

Instantly share code, notes, and snippets.

@migrs
Last active January 6, 2020 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save migrs/cc9107f68ac339622f03366771a682a5 to your computer and use it in GitHub Desktop.
Save migrs/cc9107f68ac339622f03366771a682a5 to your computer and use it in GitHub Desktop.
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