Skip to content

Instantly share code, notes, and snippets.

@kmcintyre
Last active December 24, 2015 23:59
Show Gist options
  • Save kmcintyre/6884078 to your computer and use it in GitHub Desktop.
Save kmcintyre/6884078 to your computer and use it in GitHub Desktop.
python script for setting the route53 mx record.
"""
Requeriments:
$ sudo pip install boto
Edit ~/.boto to use your AWS credentials
This is a script that updates the mx record for a domain to the ec2 instance public dns
"""
import sys
from boto.route53.connection import Route53Connection
from boto.route53.exception import DNSServerError
from boto.route53.record import ResourceRecordSets
HOSTED_ZONE = 'Z3JWHG9C5MS86I'
DOMAIN_NAME = 'scewpt.com'
CNAME = 'mail.scewpt.com'
MX_PRIORITY = '20'
from twisted.web.client import Agent
from twisted.internet import reactor, defer
from pyscewpt.utilities import OneLiner
def mx_work(ec2_instance_name):
new_mx = '%s %s' % (MX_PRIORITY, ec2_instance_name)
print 'New MX value:', new_mx
conn = Route53Connection()
try:
print 'hosted zone:', HOSTED_ZONE
zone = conn.get_hosted_zone(HOSTED_ZONE)
print 'zone domain:', zone['GetHostedZoneResponse']['HostedZone']['Name']
except DNSServerError as e:
print 'Zone Not Found:', DOMAIN_NAME, e
sys.exit(1)
def set_mx():
rrs = ResourceRecordSets(conn, HOSTED_ZONE, '')
print 'set mx'
response = conn.get_all_rrsets(HOSTED_ZONE, 'MX', DOMAIN_NAME, maxitems=1)[0]
if len( response.resource_records ) > 0:
if new_mx in response.resource_records:
print 'Nothing to do for MX'
return
remove = rrs.add_change("DELETE", DOMAIN_NAME, 'MX', response.ttl)
for old_value in response.resource_records:
print 'remove mx:', old_value
remove.add_value(old_value)
print 'add mx'
add = rrs.add_change("CREATE", DOMAIN_NAME, 'MX', response.ttl)
add.add_value(new_mx)
try:
rrs.commit()
except Exception as e:
print 'Changes cannot be made:', e
sys.exit(1)
def set_cname():
rrs = ResourceRecordSets(conn, HOSTED_ZONE, '')
print 'set cname'
response = conn.get_all_rrsets(HOSTED_ZONE, 'CNAME', CNAME, maxitems=1)[0]
if len( response.resource_records ) > 0:
if ec2_instance_name in response.resource_records:
print 'Nothing to do for CNAME'
return
remove = rrs.add_change("DELETE", CNAME, 'CNAME', response.ttl)
for old_value in response.resource_records:
print 'remove cname:', old_value
remove.add_value(old_value)
print 'add cname'
add = rrs.add_change("CREATE", CNAME, 'CNAME', response.ttl)
add.add_value(ec2_instance_name)
try:
rrs.commit()
except Exception as e:
print 'Changes cannot be made:', e
sys.exit(1)
set_mx()
set_cname()
if __name__ == '__main__':
Agent(reactor).request('GET', 'http://169.254.169.254/latest/meta-data/public-hostname', None, None).addCallback(lambda res: res.deliverBody(OneLiner(defer.Deferred().addCallback(mx_work)))).addCallback(lambda ign: reactor.stop())
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment