Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#! /usr/bin/env python3
from ns1 import NS1
import pprint
import subprocess
import keyboard
NS1_API_KEY = "<INSERT API KEY>"
ZONE_NAME = '<INSERT ZONE NAME>'
TF_ZONE_NAME = ZONE_NAME.replace(".","_")
TF_FILE = ZONE_NAME.replace(".","_") + ".tf"
api = NS1(apiKey=NS1_API_KEY)
zone = api.loadZone(ZONE_NAME)
# print(zone.data)
with open(TF_FILE, "a") as f:
for record in zone['records']:
domain = record['domain']
f.write("\nresource \"ns1_record\" \"" + domain.replace(".", "_") + "_" + record['type'] + "\" {")
f.write("\n zone = \"${ns1_zone." + TF_ZONE_NAME + ".zone}\"")
f.write("\n domain = \"")
sub_dom = domain.split(".")
for s in sub_dom:
if s == ZONE_NAME.split(".")[0]:
break
else:
f.write(s + ".")
f.write("${ns1_zone." + TF_ZONE_NAME + ".zone}\"")
f.write("\n type = \"" + record['type'] + "\"")
f.write("\n use_client_subnet = \"false\"")
for ans in record['short_answers']:
f.write("\n answers {")
f.write("\n answer = \"" + ans + "\"")
f.write("\n }")
f.write("\n}")
f.close()
broken = []
for record in zone['records']:
try:
domain = record['domain']
# print(record)
print("Command: ")
print("terraform", "import", "ns1_record." + domain.replace(".", "_") + "_" + record['type'], ZONE_NAME + "/" + domain + "/" + record['type'])
subprocess.call(["terraform", "import", "ns1_record." + domain.replace(".", "_") + "_" + record['type'], ZONE_NAME + "/" + domain + "/" + record['type']])
keyboard.press('enter')
except Exception as e:
broken.append(record)
print(broken)
print("Exception while importing- ", e)
@ionigman

This comment has been minimized.

Copy link

@ionigman ionigman commented Aug 29, 2019

You can either insert the following three lines at line 19,
f.write("\nresource "ns1_zone" "" + TF_ZONE_NAME + "" {")
f.write("\nzone = "" + ZONE_NAME +""")
f.write("\n}")
Or you'll need a .tf file with only the zone config in a format compatible with this script.

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