Skip to content

Instantly share code, notes, and snippets.

@james-ingold
Created July 29, 2021 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james-ingold/5458f137b95a34aff4f5676daec23acd to your computer and use it in GitHub Desktop.
Save james-ingold/5458f137b95a34aff4f5676daec23acd to your computer and use it in GitHub Desktop.
Python script to bulk update DNS entries in Route53
#!/usr/bin/env python
"""
Bulk Update DNS on AWS Route53
"""
import argparse
import sys
import boto3
parser = argparse.ArgumentParser()
parser.add_argument("--zoneId", type=str, default="", help="Route53 Zone Id, recommend setting this as an environment variable")
parser.add_argument("--hostname", type=str, default="", help="The hostname to update example.domain.com")
parser.add_argument("--dns", type=str, default="", help="The new dns value")
args = parser.parse_args()
route53 = boto3.client('route53')
zoneid = args.zoneId
hostname = args.hostname
CNAME = args.dns
if not zoneid or not hostname or not CNAME:
print("Please provide a zone id, hostname and new dns")
return
#
# updatedns - Updates DNS for a hos name
#
def updatedns(hostname, newdns):
# Add trailing dot to hostname if it doesn't have one
if hostname[-1:] != ".":
hostname += "."
print('Hostname: %s' % hostname)
print('Current DNS: %s' % newdns)
# If you only have one hosted zone, you can do something like this to look in the zone
# Initialize the connection to AWS Route53
# route53 = Route53Connection()
# route53zones = route53.get_all_hosted_zones()
# route53zones = route53.list_resource_record_sets(HostedZoneId=)
sets = route53.list_resource_record_sets(HostedZoneId=zoneid)
for rset in sets['ResourceRecordSets']:
if rset['Name'] == hostname and rset['Type'] == 'CNAME':
curdnsrecord = rset['ResourceRecords']
print(curdnsrecord)
if type(curdnsrecord) in [list, tuple, set]:
for record in curdnsrecord:
curdns = record
# print('Current DNS CNAME: %s' % curdns)
curttl = rset['TTL']
# print('Current DNS TTL: %s' % curttl)
if curdns != newdns:
# UPSERT the record
print('Updating %s' % hostname)
route53.change_resource_record_sets(
HostedZoneId=zoneid,
ChangeBatch={
'Changes': [
{
'Action': 'UPSERT',
'ResourceRecordSet': {
'Name': hostname,
'Type': 'CNAME',
'TTL': curttl,
'ResourceRecords': [
{
'Value': newdns
}
]
}
}
]
}
)
try:
updatedns(hostname, CNAME)
except:
print('DNS Update failed. Check credentials or IAM roles.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment