-
-
Save ueki-kazuki/24b996d102687a4dd169 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 'logger' | |
require 'yaml' | |
begin | |
require 'aws/profile_parser' | |
rescue LoadError; end | |
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('--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.each do |sec| | |
security_groups[sec.name] = [] | |
dict[sec.id] = sec.name | |
end | |
# EC2 | |
ec2.instances.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.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.each do |lb| | |
lb.security_groups.each do |sec| | |
security_groups[sec.name].push(lb.name) | |
end | |
end | |
end | |
# Output | |
puts security_groups.to_yaml |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment