Created
January 21, 2017 19:34
-
-
Save pauloprea/988ce9d70b91503dcd3cfbcd7ef18d92 to your computer and use it in GitHub Desktop.
Dynamic DNS Script for Amazon Lambda (to use with Amazon API Gateway)
This file contains 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 re | |
import boto3 | |
def is_valid_host(host): | |
if len(host) > 255: | |
return False | |
if host[-1] == ".": | |
host = host[:-1] | |
allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) | |
return all(allowed.match(x) for x in host.split(".")) | |
def is_valid_ip(ip): | |
return re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip) | |
def lambda_handler(event, context): | |
host = event["host"] | |
cname = host[:host.find(".")] | |
hosted_zone = host[host.find(".")+1:] | |
new_ip = event["ip"] | |
print "Processing request to update %s with ip %s" % (host, new_ip) | |
route53 = boto3.client('route53') | |
try: | |
print ("Validating inputs... "), | |
if not (is_valid_host(host) and is_valid_ip(new_ip)): | |
raise | |
print ("Success") | |
print ("Retrieving hosted zone..."), | |
response = route53.list_hosted_zones_by_name( | |
DNSName=hosted_zone, | |
MaxItems='1' | |
) | |
r53hosted_zone = route53.get_hosted_zone( | |
Id=response["HostedZones"][0]["Id"] | |
) | |
print ("Success") | |
print ("Checking against existing IP..."), | |
r53resource_record_set = route53.list_resource_record_sets( | |
HostedZoneId = r53hosted_zone["HostedZone"]["Id"], | |
StartRecordName = host, | |
MaxItems = "1" | |
) | |
retMsg = "" | |
if r53resource_record_set["ResourceRecordSets"][0]["ResourceRecords"][0]["Value"]==new_ip: | |
print ("IP hasn't changed. Exiting.") | |
return "nochg %s" % new_ip | |
print("Success") | |
print ("Updating route53 record for %s..." % (host)), | |
dns_changes = { | |
'Changes': [ | |
{ | |
'Action': 'UPSERT', | |
'ResourceRecordSet': { | |
'Name': host , | |
'Type': 'A', | |
'ResourceRecords': [ | |
{ | |
'Value': new_ip | |
} | |
], | |
'TTL': 300 | |
} | |
} | |
] | |
} | |
response = route53.change_resource_record_sets( | |
HostedZoneId=r53hosted_zone["HostedZone"]["Id"], | |
ChangeBatch=dns_changes | |
) | |
print("Success") | |
return "good %s" % (new_ip) | |
except: | |
print ("Failed") | |
return "dnserr" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment