Skip to content

Instantly share code, notes, and snippets.

@buchi
Last active September 17, 2019 14:48
Show Gist options
  • Save buchi/9265307f2a609687c993145887bf7414 to your computer and use it in GitHub Desktop.
Save buchi/9265307f2a609687c993145887bf7414 to your computer and use it in GitHub Desktop.
Convert JSON DNS Zone File to Route 53
import json
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument('dir', help='Directory containing zone files')
options = parser.parse_args()
path = os.path.abspath(options.dir)
for filename in os.listdir(path):
if not filename.endswith('.json') or filename.endswith('_aws.json'):
continue
infile = os.path.join(path, filename)
outfile = os.path.join(path, '_aws.'.join(filename.rsplit('.', 1)))
with open(infile, 'r') as jsonfile:
data = json.load(jsonfile)
entries = data['results']
domain = entries[0].get('domain')
entries_by_type_name = {}
for entry in entries:
content = entry["content"]
if entry["type"] == "MX":
content = str(entry["prio"]) + " " + content
key = (entry["name"], entry["type"], entry["ttl"])
if key in entries_by_type_name:
entries_by_type_name[key].append(content)
else:
entries_by_type_name[key] = [content]
aws = {
"Comment": "Import DNS records for {}".format(domain),
"Changes": [
],
}
for key, value in entries_by_type_name.items():
if key[1] in ['SOA', 'NS']:
continue
aws_entry = {
"Action": "CREATE",
"ResourceRecordSet": {
"Type": key[1],
"Name": key[0],
"TTL": key[2],
}
}
values = [{"Value": v} for v in value]
aws_entry["ResourceRecordSet"]["ResourceRecords"] = values
aws['Changes'].append(aws_entry)
with open(outfile, 'w') as jsonfile:
json.dump(aws, jsonfile, indent=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment