Skip to content

Instantly share code, notes, and snippets.

@MahmoudDolah
Last active August 29, 2019 19:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MahmoudDolah/7e31dc8f61c513119948dca56ad36c2f to your computer and use it in GitHub Desktop.
Save MahmoudDolah/7e31dc8f61c513119948dca56ad36c2f to your computer and use it in GitHub Desktop.
#! /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
Copy link

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