Last active
July 30, 2018 15:03
-
-
Save sethryder/e88c20d75063e692609083e92b30c3f1 to your computer and use it in GitHub Desktop.
simple lambda for storing cloudfront ips in parameter store for use in other places (such as nginx for where to trust X-Forwarded-For headers)
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
from botocore.vendored import requests | |
import json | |
import boto3 | |
def get_cloudfront_ips(): | |
ip_list = '' | |
d = requests.get('https://ip-ranges.amazonaws.com/ip-ranges.json').text | |
l = json.loads(d) | |
for ip_range in [x['ip_prefix'] for x in l['prefixes'] if x['service']=='CLOUDFRONT' ]: | |
ip_list += ip_range + ',' | |
return ip_list.strip(',') | |
def get_ips_from_paramter_store(key): | |
client = boto3.client('ssm') | |
response = client.get_parameter(Name=key) | |
return response['Parameter']['Value'] | |
def write_ips_to_parameter_store(key, cloudfront_ips): | |
client = boto3.client('ssm') | |
response = client.put_parameter( | |
Name=key, | |
Value=cloudfront_ips, | |
Type='StringList', | |
Overwrite=True, | |
AllowedPattern="^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?,?$" | |
) | |
def lambda_handler(event, context): | |
key = '/your/parameter_store/key' | |
parameter_store_ips = get_ips_from_paramter_store(key) | |
cloudfront_ips = get_cloudfront_ips() | |
if parameter_store_ips != cloudfront_ips: | |
print('Updating IPs in the Parameter Store') | |
write_ips_to_parameter_store(key, cloudfront_ips) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment