Last active
January 8, 2020 04:05
-
-
Save thomsh/8e76fa9582f4b794171edc11b30c00a3 to your computer and use it in GitHub Desktop.
python3 boto3 script to allow your ip on a EC2 security group (Like your dev VM, boring & recuring task)
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 python3 | |
# python3 boto3 script to allow your ip on a EC2 security group (Like your dev VM, boring & recuring task) | |
import boto3 | |
from pprint import pprint | |
import requests | |
SG_ID = 'sg-CHANGEME' # You security group ID | |
# REGION https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html | |
# or can be provided via env var or in your .aws/config | |
REGION = 'ap-southeast-2' | |
RULE_COMMENT = 'Added via my laptop script' | |
ec2 = None | |
cache_ip = None | |
def myipv4(): | |
global cache_ip | |
if cache_ip is None: | |
r = requests.get(url='http://ipinfo.io') | |
cache_ip = '{}/32'.format(r.json()['ip']) | |
return cache_ip | |
def get_rules(): | |
global ec2 | |
r = ec2.describe_security_groups(GroupIds=[SG_ID]) | |
return r['SecurityGroups'][0]['IpPermissions'] | |
def clean_rules(): | |
global ec2 | |
found_my_ip = False | |
for rule in get_rules(): | |
if rule['IpProtocol'] == '-1': | |
print('All IpProtocol found :') | |
pprint(rule) | |
for cidr in rule['IpRanges']: | |
if cidr['CidrIp'] != myipv4(): | |
ec2.revoke_security_group_ingress( | |
CidrIp=cidr['CidrIp'], | |
GroupId=SG_ID, | |
IpProtocol='-1' | |
) | |
print('rule delete for ip : {}'.format(cidr['CidrIp'])) | |
else: | |
found_my_ip = True | |
return found_my_ip | |
def add_rule(): | |
global ec2p | |
data = ec2.authorize_security_group_ingress( | |
GroupId=SG_ID, | |
IpPermissions=[{'IpProtocol': '-1', | |
'IpRanges': [{'CidrIp': myipv4(), | |
'Description': RULE_COMMENT | |
}] | |
}] | |
) | |
print('Ingress Successfully Set %s' % data) | |
if __name__ == "__main__": | |
ec2 = boto3.client('ec2', region_name=REGION) | |
print('Updating rules') | |
if not clean_rules(): | |
print('Ip {} not found, adding..'.format(myipv4())) | |
add_rule() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment