Skip to content

Instantly share code, notes, and snippets.

@ueki-kazuki
Forked from mochizuki-masao/secgroup_search.rb
Last active August 29, 2015 14:01
Show Gist options
  • Save ueki-kazuki/04162c332d81c6eaf76b to your computer and use it in GitHub Desktop.
Save ueki-kazuki/04162c332d81c6eaf76b to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'aws-sdk'
require 'optparse'
require 'logger'
require 'yaml'
begin
require 'aws/profile_parser'
rescue LoadError; end
config = {}
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.on('-e', '--expand') { |v| config[:expand] = true }
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
if config[:expand] then
security_groups.keys.sort.each do |sec|
if security_groups[sec].size == 0 then
puts "#{sec}"
else
security_groups[sec].sort.each do |instance|
puts "#{sec} #{instance}"
end
end
end
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