Skip to content

Instantly share code, notes, and snippets.

@sajal
Created January 6, 2012 20:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sajal/1572219 to your computer and use it in GitHub Desktop.
Save sajal/1572219 to your computer and use it in GitHub Desktop.
DYI dynamic DNS using python/boto
from boto.route53.connection import Route53Connection
import urllib2
from syslog import syslog
# ======= CONFIG ========
AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXXXXXX'
AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
DDNSNAME = "foo.example.com." # Should end in period
ZONEID = "XXXXXXXXX"
# ===== END CONFIG ======
def wtf_myip():
ip = urllib2.urlopen("http://wtfismyip.com/text").read().strip()
return ip
def update_route53():
route53 = Route53Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
rr = route53.get_all_rrsets(ZONEID)
oldips = []
for r in rr:
#print r.name
if r.name == DDNSNAME:
oldips += r.resource_records
deletechanges = ""
newip = wtf_myip()
if oldips == [newip]:
#No need to update!!!
syslog("Record in route53 matches current ip")
else:
for ip in oldips:
deletechanges += """
<Change>
<Action>DELETE</Action>
<ResourceRecordSet>
<Name>%s</Name>
<Type>A</Type>
<TTL>60</TTL>
<ResourceRecords>
<ResourceRecord>
<Value>%s</Value>
</ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
""" %(DDNSNAME, ip)
#print deletechanges
xml = """<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2011-05-05/">
<ChangeBatch>
<Comment>Add record</Comment>
<Changes>
%s
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>%s</Name>
<Type>A</Type>
<TTL>60</TTL>
<ResourceRecords>
<ResourceRecord>
<Value>%s</Value>
</ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>""" % (deletechanges, DDNSNAME, newip)
#print xml
c = route53.change_rrsets(ZONEID,xml)
syslog(c["ChangeResourceRecordSetsResponse"]["ChangeInfo"]["Id"].replace("/change/", ""))
if __name__ == "__main__":
update_route53()
@masayang
Copy link

You could use http://169.254.169.254/latest/meta-data/public-ipv4 instead of wtfismyip.com to get global IP address of the instance.

@dsoprea
Copy link

dsoprea commented Jun 14, 2014

Consider using ResourceRecordSets to avoid XML completely: http://www.petekeen.net/how-and-why-im-not-running-my-own-dns

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