module Terraformer module Resource class CloudWatchAlarm include Terraformer::Templating def self.execute(options, client: Aws::CloudWatch::Client) self.new(options, client).execute end def initialize(options, client) @credentials = Terraformer::Credentials::Aws.get_from_options(options) @client = client.new(@credentials) end def execute { tf: tf, tfstate: tfstate } end private def tf apply_template("tf/cloud_watch_alarm") end def tfstate alarms.inject({}) do |resources, alarm| resources["aws_cloudwatch_metric_alarm.#{alarm.normalized_name}"] = { "type" => "aws_cloudwatch_metric_alarm", "depends_on" => [], "primary" => { "id" => alarm.alarm_name, "attributes" => alarm_attributes(alarm) }, "deposed" => [], "provider" => "" } resources end end def alarm_attributes(alarm) attributes = { "actions_enabled" => alarm.actions_enabled.to_s, "alarm_description" => sanitize(alarm.alarm_description), "alarm_name" => alarm.alarm_name, "comparison_operator" => alarm.comparison_operator, "evaluation_periods" => alarm.evaluation_periods.to_s, "id" => alarm.alarm_name, "metric_name" => alarm.metric_name, "namespace" => alarm.namespace, "period" => alarm.period.to_s, "statistic" => alarm.statistic, "threshold" => alarm.threshold.to_s, "unit" => sanitize(alarm.unit) } add_checksummed_attributes(attributes, alarm) end private def alarms @alarms ||= begin aws_response = @client.describe_alarms.map(&:metric_alarms).flatten aws_response.inject([]) do |alarms, alarm| alarm = alarm.to_h alarm[:normalized_name] = Terraformer::Normalizer.module_name(alarm[:alarm_name]) alarm[:dimensions].map! { |d| OpenStruct.new(d) } alarms << OpenStruct.new(alarm) end end end def sanitize(argument) argument.nil? ? "" : argument end def add_checksummed_attributes(attributes, alarm) %w(insufficient_data_actions alarm_actions ok_actions dimensions).each do |action| attribute = alarm.send(action.to_sym) attributes["#{action}.#"] = attribute.size.to_s attribute.each do |attr| if attr.is_a? String checksum = Zlib.crc32(attr) value = attr else checksum = attr.name value = attr.value end attributes["#{action}.#{checksum}"] = value end end attributes end end end end