Last active
May 3, 2018 04:46
-
-
Save mochizuki-masao/b7a5dc19c28862019550 to your computer and use it in GitHub Desktop.
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 'aws-sdk' | |
require 'optparse' | |
require 'yaml' | |
require 'json' | |
begin | |
require 'aws/profile_parser' | |
rescue LoadError; end | |
format = :yaml | |
ARGV.options do |opt| | |
begin | |
aws_opts = {} | |
is_debug = false | |
opt.on('-h', '--help') { puts opt.help; exit 0 } | |
opt.on('-k', '--access-key ACCESS_KEY') { |v| aws_opts[:access_key_id] = v } | |
opt.on('-s', '--secret-key SECRET_KEY') { |v| aws_opts[:secret_access_key] = v } | |
opt.on('-r', '--region REGION') { |v| aws_opts[:region] = v } | |
opt.on('-f', '--format FORMAT') { |v| format = v.to_sym } | |
opt.on('--debug') { is_debug = true} | |
opt.on('--profile PROFILE') { |v| parser = AWS::ProfileParser.new; aws_opts = parser.get(v) } | |
opt.parse! | |
if aws_opts.empty? | |
puts opt.help | |
exit 1 | |
end | |
AWS.config(aws_opts) | |
if is_debug | |
AWS.config(:log_level => :debug, :logger => Logger.new($stdout)) | |
end | |
rescue => e | |
$stderr.puts e | |
exit 1 | |
end | |
end | |
# list all security groups and make it Hash | |
security_groups = {} | |
# dictionary for mapping SecurityGroup ID and Name | |
dict = {} | |
ec2 = AWS::EC2.new | |
AWS.memoize do | |
ec2.security_groups.sort_by{|sec| sec.name }.each do |sec| | |
security_groups[sec.name] = [] | |
dict[sec.id] = sec.name | |
end | |
# EC2 | |
ec2.instances.sort_by{|i| i.tags.Name }.each do |i| | |
i.security_groups.each do |sec| | |
security_groups[sec.name].push(i.tags.Name) | |
end | |
end | |
# RDS | |
# | |
# use bare client class because AWS::RDS::Instance | |
# does not have "vpc_security_group_id" property | |
rds = AWS::RDS::Client.new | |
db_instances = rds.describe_db_instances.db_instances | |
db_instances.sort_by{|i| i.db_instance_identifier }.each do |i| | |
i.vpc_security_groups.each do |sec| | |
security_groups[dict[sec.vpc_security_group_id]].push(i.db_instance_identifier) | |
end | |
end | |
# ELB | |
elb = AWS::ELB.new | |
elb.load_balancers.sort_by{|lb| lb.name }.each do |lb| | |
lb.security_groups.each do |sec| | |
security_groups[sec.name].push(lb.name) | |
end | |
end | |
end | |
# Output | |
case format | |
when :expand | |
security_groups.each do |sec, instances| | |
if instances.size == 0 then | |
puts "#{sec}" | |
else | |
instances.each do |instance| | |
puts "#{sec} #{instance}" | |
end | |
end | |
end | |
when :json | |
puts security_groups.to_json | |
else | |
puts security_groups.to_yaml | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment