Skip to content

Instantly share code, notes, and snippets.

@Seraf
Created February 10, 2015 16:03
Show Gist options
  • Save Seraf/688ea17cfb9868cf024f to your computer and use it in GitHub Desktop.
Save Seraf/688ea17cfb9868cf024f to your computer and use it in GitHub Desktop.
Register automatically an ec2 instance to route 53. The domain is pushed with DHCP option and is stored in the resolv.conf file
#!/usr/bin/env python
import urllib2
import boto
import logging
import socket
logger = logging.getLogger(__name__)
handler = logging.FileHandler('/var/log/route53.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Use the first domain of resolv.conf as main domain to find route 53 zone
resolv = '/etc/resolv.conf'
look_for = 'search'
hostname = socket.gethostname()
domain = None
local_ipv4 = urllib2.urlopen('http://169.254.169.254//latest/meta-data/local-ipv4')
ipv4 = local_ipv4.read()
with open(resolv, "r") as file_to_read:
for line in file_to_read:
if look_for in line:
resolv_array = line.split()
domain = resolv_array[1]
conn = boto.connect_route53()
try:
zone = conn.get_hosted_zone_by_name(domain)
except DNSServerError:
logger.error('Zone Not Found')
sys.exit(1)
from boto.route53.zone import Zone
vpc_zone = Zone(conn, zone['GetHostedZoneResponse']['HostedZone'])
if vpc_zone.find_records(hostname.lower() + '.' + domain + '.', 'A', 1, True):
logger.info("Entry %s already exists" % (hostname.lower() + '.' + domain + '.'))
else:
vpc_zone.add_a(name=hostname.lower() + '.' + domain + '.', value=ipv4, ttl=300)
logger.info("Adding entry: %s A %s" % (hostname.lower() + '.' + domain + '.', ipv4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment