Skip to content

Instantly share code, notes, and snippets.

@naveen-vijay
Last active March 16, 2020 08:11
Show Gist options
  • Save naveen-vijay/84b7b4a5d675592ee1d0 to your computer and use it in GitHub Desktop.
Save naveen-vijay/84b7b4a5d675592ee1d0 to your computer and use it in GitHub Desktop.
Python Boto Code to update your EC2 instance's Security Group to be in sync with your changing Public IP
# Python Boto Script to Update the EC2 security group to make the instance
# to be open to your public IP although ISP change
# Can be automated in CRON everyday
import boto
import urllib2
def get_public_ip():
ext_ip = urllib2.urlopen("http://curlmyip.com").read()
return ext_ip.strip()
sg_name = '<your security group name>' #enter your Security Group's NAME
ec2 = boto.connect_ec2()
sg = ec2.get_all_security_groups(groupnames=sg_name)
sg = sg[0]
#remove existing 22 SSH rules - old CIDR IP
for rule in sg.rules:
if str(rule.from_port) == '22':
ec2.revoke_security_group(group_name=sg_name,
ip_protocol='tcp',
from_port='22',
to_port='22',
cidr_ip=rule.grants[0])
#Authorize today's Public IP
ec2.authorize_security_group(group_name=sg_name,
ip_protocol='tcp',
from_port='22',
to_port='22',
cidr_ip=get_public_ip()+"/32")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment