Skip to content

Instantly share code, notes, and snippets.

Last active Jan 6, 2020
What would you like to do?
ec2 のインスタンス名をホストファイルに登録する
#!/usr/bin/env ruby
require 'json'
require "optparse"
options = { update: true }
argv = [] do |opt|
opt.on("--dry-run") { |v| options[:update] = false }
argv = opt.parse!(ARGV)
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 = {|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']
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
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