Skip to content

Instantly share code, notes, and snippets.

@vrypan
Last active August 12, 2021 21:43
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save vrypan/4341878 to your computer and use it in GitHub Desktop.
Save vrypan/4341878 to your computer and use it in GitHub Desktop.
Python script to add/update an A record at amazon area53 DNS service, using current IP. (ie, dyndns replacement)
from area53 import route53
from boto.route53.exception import DNSServerError
import requests
import sys
from datetime import datetime
# Modified from https://markcaudill.me/blog/2012/07/dynamic-route53-dns-updating-with-python/
domain = 'domain.tld'
subdomain = 'subdomain_name'
def get_public_ip():
r = requests.get('http://icanhazip.com')
return r.text.rstrip()
fqdn = '%s.%s' % (subdomain, domain)
zone = route53.get_zone(domain)
arec = zone.get_a(fqdn)
new_value = get_public_ip()
datestr = '"Last update %s."' % datetime.utcnow().strftime('%Y-%m-%d %H:%M')
if arec:
old_value = arec.resource_records[0]
if old_value == new_value:
print '%s is current. (%s)' % (fqdn, new_value)
sys.exit(0)
print 'Updating %s: %s -> %s' % (fqdn, old_value, new_value)
try:
zone.update_a(fqdn, new_value, 900)
zone.update_txt(fqdn, datestr, 900)
except DNSServerError:
# This can happen if the record did not already exist. Let's
# try to add_a in case that's the case here.
zone.add_a(fqdn, new_value, 900)
zone.add_txt(fqdn, datestr, 900)
else:
zone.add_a(fqdn, new_value, 900)
zone.add_txt(fqdn, datestr, 900)
@dhardiker
Copy link

dhardiker commented Mar 12, 2017

I use the AWS CLI for this in a simple shell script:

#!/bin/sh
export AWS_ACCESS_KEY_ID="redacted"
export AWS_SECRET_ACCESS_KEY="redacted"

AWS_ROUTE53_ZONEID="redacted"
HOSTNAME="sub.domain.com"
TTL="600"
IP=`curl http://ifconfig.co/ 2>/dev/null`

/path/to/aws route53 change-resource-record-sets --hosted-zone-id $AWS_ROUTE53_ZONEID --change-batch "{ \"Changes\": [ { \"Action\": \"UPSERT\", \"ResourceRecordSet\": { \"Name\": \"$HOSTNAME\", \"Type\": \"A\", \"TTL\": $TTL, \"ResourceRecords\": [ { \"Value\": \"$IP\" } ] } } ] }"
echo "Updated the DNS Zone to $IP"

You'll need to make sure that the AWS user you're using has route53:ChangeResourceRecordSets access allowed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment