Skip to content

Instantly share code, notes, and snippets.

@aughban
Created May 5, 2013 14:41
Show Gist options
  • Save aughban/5520996 to your computer and use it in GitHub Desktop.
Save aughban/5520996 to your computer and use it in GitHub Desktop.
a quick script to help you avoid setting up security groups using 0.0.0.0/8 for your own instances.
require 'aws-sdk'
require 'json'
require 'open-uri'
# Lets get our IP first
ip = JSON.parse(open('http://jsonip.com').string)['ip'] + '/32'
# You'll need to provide details that allow for API access to SG's.
ACCOUNT = {
:access_key_id => '',
:secret_access_key => '',
:region => 'eu-west-1'
}
# take it as an argument or provide a default value
SG = ARGV[0] || 'sg-xyz'
AWS.config(access_key_id: ACCOUNT[:access_key_id], secret_access_key: ACCOUNT[:secret_access_key] , region: ACCOUNT[:region])
ec2 = AWS::EC2.new
# This bit lets us determine if it's a security group name or a security group id.
if /sg-\w+/.match(SG).nil?
sg = ec2.security_groups.filter('group-name',SG).first
if sg.nil?
abort("The security group %s doesn't exist therefore we are unable to continue" % SG)
end
else
sg = ec2.security_groups[SG]
if not sg.exists?
abort("The security group %s doesn't exist therefore we are unable to continue" % SG)
end
end
sg.ingress_ip_permissions.each do |ip_rule|
# Add a new rule based on the old one
begin
sg.authorize_ingress(ip_rule.protocol, ip_rule.port_range, ip)
puts "Adding rule to allow %s to connect on %s" % [ip,ip_rule.port_range]
rescue AWS::EC2::Errors::InvalidPermission::Duplicate
# This is for when you do it but your IP hasn't changed. Prevents unwanted errors/crashes.
next
end
# out with the old!
ip_rule.revoke
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment