Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert tfstate to tf for datadog_monitor on Terraform Datadog Provider
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
import codecs
#reload(sys) # for OSX
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
#sys.setdefaultencoding('utf-8') # for OSX
f = open('terraform.tfstate', 'r')
data = json.load(f)
#print json.dumps(data)
f_downtime = open('downtime.tf', 'w');
f_monitor = open('monitor.tf', 'w');
f_user = open('user.tf', 'w');
for module in data["modules"]:
for resource in module["resources"]:
resource_values = resource.split(".")
if resource_values[0] == "datadog_downtime":
fo = f_downtime
elif resource_values[0] == "datadog_monitor":
fo = f_monitor
elif resource_values[0] == "datadog_user":
fo = f_user
else:
continue
fo.write ("resource \"" + resource_values[0] + "\" \"" + resource_values[1] + "\" {\n")
values = module["resources"][resource]["primary"]
if resource_values[0] == "datadog_downtime":
kv_keys = ["start", "end", "message", "active"]
list_keys = ["scope"]
object_keys = []
other_keys = ["recurrence"]
elif resource_values[0] == "datadog_monitor":
kv_keys = ["type", "name", "query", "message", "escalation_message", "notify_no_data", "new_host_delay", "evaluation_delay", "no_data_timeframe", "renotify_interval", "notify_audit", "timeout_h", "include_tags", "require_full_window", "locked"]
list_keys = ["tags"]
object_keys = ["thresholds", "silenced"]
other_keys = []
elif resource_values[0] == "datadog_user":
kv_keys = ["disabled", "email", "handle", "is_admin", "name", "role", "disabled", "verified"]
list_keys = []
object_keys = []
other_keys = []
else:
fo.write ("#!!! " + resource_values[0] + " not defined.\n")
# key value
for key in kv_keys:
if key in values["attributes"]:
value = values["attributes"][key]
value = value.replace('\n', '\\n')
value = value.replace('"', '\\"')
fo.write (" " + key + " = \"" + value + "\"\n")
# list
for key in list_keys:
keysuffix = "#"
if (key + "." + keysuffix in values["attributes"]) and (int(values["attributes"][key + "." + keysuffix]) > 0):
value = key + " = ["
for i in range(0, int(values["attributes"][key + "." + keysuffix])):
if i > 0:
value = value + ","
value = value + "\"" + values["attributes"][key + "." + str(i)] + "\""
fo.write (" " + value + "]\n")
# object
for key in object_keys:
keysuffix = "%"
if (key + "." + keysuffix in values["attributes"]) and (int(values["attributes"][key + "." + keysuffix]) > 0):
fo.write (" " + key + " {\n")
if key == "thresholds":
for subkey in ["critical", "critical_recovery", "warning", "warning_recovery", "ok"]:
if key + "." + subkey in values["attributes"]:
fo.write (" " + subkey + " = " + values["attributes"][key + "." + subkey] + "\n")
elif key == "silenced":
for subkey in values["attributes"]:
if subkey.startswith(key + ".") and subkey != key + "." + keysuffix:
subkeys = subkey.split(".")
del subkeys[0]
value = ".".join(map(str, subkeys))
fo.write (" \"" + value + "\" = " + "\"" + values["attributes"][subkey] + "\"\n")
else:
fo.write ("#!!! " + key + " on " + resource_values[0] + " not defined.\n")
fo.write (" }\n")
fo.write ("}\n")
f_downtime.close()
f_monitor.close()
f_user.close()
f.close()
@ZimbiX

This comment has been minimized.

Copy link

@ZimbiX ZimbiX commented Apr 9, 2018

Thanks for this! It made importing super easy =)
I had to change a couple of things: https://gist.github.com/ZimbiX/65025e1d49603e148734ebbfcb19cf77

To generate the Terraform import commands to run before using this script, here's a snippet of JS I wrote:

// Run on https://app.datadoghq.com/monitors/manage
var numFromLink = (link) => (link.replace('https://app.datadoghq.com/monitors#',''))
var idFromName = (name) => (name.toLowerCase().replace(/[\(\)\[\]\{\}']/g, '').replace(/[ \.:]/g, '_').replace('%', 'pct'))
$('div.ManageMonitors-Table-cell.ManageMonitors-Table-column-name-cell > a').toArray()
  .map(x => [idFromName(x.innerText), numFromLink(x.href)])
  .map(x => `terraform import datadog_monitor.${x[0]} ${x[1]}`).join("\n")
@htnosm

This comment has been minimized.

Copy link
Owner Author

@htnosm htnosm commented Apr 15, 2018

@ZimbiX
Thank you for your feedback.
I reflected in the code.

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