module Terraformer module Resource class DatadogMonitor include Terraformer::Templating def self.execute(options, client: Dogapi::Client) self.new(options, client).execute end def initialize(options, client) @credentials = Terraformer::Credentials::Datadog.get_from_options(options) @client = client.new(@credentials[:api_key], @credentials[:app_key]) end def execute { tf: tf, tfstate: tfstate } end private def tf apply_template("tf/datadog_monitor") end def tfstate monitors.inject({}) do |resources, monitor| resources["datadog_monitor.#{monitor["normalized_name"]}"] = { "type" => "datadog_monitor", "depends_on" => [], "primary" => { "id" => monitor["id"].to_s, "attributes" => monitor_attributes(monitor), "meta" => {}, "tainted" => false }, "deposed" => [], "provider" => "" } resources end end private def monitors @monitors ||= begin response = check_response(@client.get_all_monitors) response.each do |monitor| monitor["normalized_name"] = Terraformer::Normalizer.module_name(monitor["name"]) # Fix missing thresholds if monitor["options"]["thresholds"].nil? critical = monitor["query"].split.last monitor["options"]["thresholds"] = { "critical" => critical } else monitor["options"]["thresholds"].each { |k, v| monitor["options"]["thresholds"][k] = v.round } end end response end end def check_response(response) unless response[0] == "200" raise "[ERROR] Received bad response form Datadog. code: #{response[0]} response: #{response[1]}" end response[1] end def monitor_attributes(monitor) attributes = { "id" => monitor["id"], "name" => monitor["name"], "type" => monitor["type"], "message" => monitor["message"], "escalation_message" => monitor["escalation_message"], "query" => monitor["query"], "notify_no_data" => monitor["options"]["notify_no_data"], "no_data_timeframe" => monitor["options"]["no_data_timeframe"], "renotify_interval" => monitor["options"]["renotify_interval"], "notify_audit" => monitor["options"]["notify_audit"], "timeout_h" => monitor["options"]["timeout_h"], "include_tags" => monitor["options"]["include_tags"], "require_full_window" => monitor["options"]["name"], "locked" => monitor["options"]["locked"] } %w(silenced thresholds).each do |argument| option = monitor["options"][argument] next if option.nil? attributes["#{argument}.%"] = option.length option.each { |k, v| attributes["#{argument}.#{k}"] = v } end attributes["tags.%"] = monitor["tags"].length monitor["tags"].each { |tag| attributes["tags.#{tag.split(":")[0]}"] = tag.split(":")[0] } sanitize_monitor(attributes) end def sanitize_monitor(attributes) attributes = Hash[ attributes.sort_by { |k, v| k }] attributes.each do |key, value| attributes[key] = value.to_s end %w(include_tags locked require_full_window).each do |attribute| attributes[attribute] = "false" if attributes[attribute] == "" end attributes end end end end