Last active
February 4, 2021 09:20
-
-
Save erijpkema/11695b40321119447af3dbd154fe9d12 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import boto3 | |
import requests | |
from datetime import datetime | |
""" | |
Dynamic DNS updater. | |
Simple boto script that will update a dns record in AWS | |
into the current public ip. | |
""" | |
domain = '' | |
subdomain = '' | |
HostedZoneId = '' | |
def get_public_ip(): | |
""" | |
return the current public ip. | |
""" | |
r = requests.get('http://icanhazip.com') | |
return r.text.rstrip() | |
def add_cname_record(hosted_zone_id, client, name, value, action): | |
""" | |
Add/update an A record. | |
""" | |
response = client.change_resource_record_sets( | |
HostedZoneId=hosted_zone_id, | |
ChangeBatch={ | |
'Comment': | |
'add %s -> %s' % (name, value), | |
'Changes': [{ | |
'Action': action, | |
'ResourceRecordSet': { | |
'Name': name, | |
'Type': 'A', | |
'TTL': 300, | |
'ResourceRecords': [{ | |
'Value': value | |
}] | |
} | |
}] | |
}) | |
if __name__ == '__main__': | |
route53 = boto3.client('route53') | |
current_ip = get_public_ip() | |
try: | |
with open('cur_ip') as f: | |
record_ip = f.read() | |
except FileNotFoundError: | |
record_ip = None | |
if record_ip != current_ip: | |
add_cname_record( | |
HostedZoneId, | |
client=route53, | |
name=f'{subdomain}.{domain}', | |
value=current_ip, | |
action='UPSERT') | |
with open('cur_ip', 'w') as f: | |
f.write(current_ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment