Last active
January 2, 2018 13:22
-
-
Save pkazmierczak/bbb735cdccc485d0baa2f3dc08389a26 to your computer and use it in GitHub Desktop.
lambda function for automatic whitelisting of AWS IPs on an SG (python3), see https://spin.atomicobject.com/2016/03/01/aws-cloudfront-security-group-lambda/ for the original
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
import copy | |
import json | |
from urllib.request import urlopen | |
import boto3 | |
def handle(event, context): | |
response = urlopen('https://ip-ranges.amazonaws.com/ip-ranges.json') | |
json_data = json.loads(response.read()) | |
new_ip_ranges = [x['ip_prefix'] for x in json_data['prefixes'] if x['service'] == 'CLOUDFRONT'] | |
ec2 = boto3.resource('ec2') | |
security_group = ec2.SecurityGroup('sg-16ffa47c') # taken from the console... | |
current_ip_ranges = [x['CidrIp'] for x in security_group.ip_permissions[0]['IpRanges']] | |
params_dict = { | |
u'PrefixListIds': [], | |
u'FromPort': 443, | |
u'IpRanges': [], | |
u'ToPort': 443, | |
u'IpProtocol': 'tcp', | |
u'UserIdGroupPairs': [] | |
} | |
authorize_dict = copy.deepcopy(params_dict) | |
for ip in new_ip_ranges: | |
if ip not in current_ip_ranges: | |
authorize_dict['IpRanges'].append({u'CidrIp': ip}) | |
revoke_dict = copy.deepcopy(params_dict) | |
for ip in current_ip_ranges: | |
if ip not in new_ip_ranges: | |
revoke_dict['IpRanges'].append({u'CidrIp': ip}) | |
print("the following new ip addresses will be added:") | |
print(authorize_dict['IpRanges']) | |
print("the following new ip addresses will be removed:") | |
print(revoke_dict['IpRanges']) | |
security_group.authorize_ingress(IpPermissions=[authorize_dict]) | |
security_group.revoke_ingress(IpPermissions=[revoke_dict]) | |
return {'authorized': authorize_dict, 'revoked': revoke_dict} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment