amazon-web-servicesterraformamazon-cloudwatchcloudwatch-alarms

metric filter is not assigned to metric alarm


I'm using terraform to set up aws cloudwatch log to send an email whenever there an error in the log.

This is how the terraform file look like:

resource "aws_cloudwatch_log_metric_filter" "error-importing-rfid-metric-filter" {
  name           = "rfid-data-import-metric-filter"
  log_group_name = var.SERVICE_NAME
  pattern        = "ERROR"
  metric_transformation {
    name      = "error-rfid-data-import"
    namespace = "DataImportErrorMetrics"
    value     = "1"
  }
}

resource "aws_cloudwatch_metric_alarm" "error-importing-rfid" {
  alarm_name          = "error-rfid-data-import"
  metric_name         = "DataImportErrorMetrics"
  threshold           = "0"
  statistic           = "Sum"
  comparison_operator = "GreaterThanThreshold"
  datapoints_to_alarm = "1"
  evaluation_periods  = "1"
  period              = "60"
  namespace           = "LogMetrics"

  alarm_actions = [aws_sns_topic.alarm.arn]
}

After run terrraform apply, I can see the filter was created and the alarm was also created. But under the alarm section, there is no alarm listed. You can see in see in the picture, there are 2 filters, the filter on the left listed an alarm name and the one on the right just show none. The one on the left was manually created on the aws console and the one on the right was from terraform. And indeed, the one that was created on the console work like a charm, but the one on the right remains in the insufficient data state the filter metric


Solution

  • I fixed the problem. the metric name is actually the metric transformation name. and the namespace in the metric_tranformation has to be the same as the namespace in aws_cloudwatch_metric_alarm. The correct snippet should be

    resource "aws_cloudwatch_log_metric_filter" "error-importing-rfid-metric-filter" {
      name           = "rfid-data-import-metric-filter"
      log_group_name = var.SERVICE_NAME
      pattern        = "ERROR"
      metric_transformation {
        name      = "error-rfid-data-import-metric"
        namespace = "LogMetrics"
        value     = "1"
      }
    }
    
    //set up the alarm
    resource "aws_cloudwatch_metric_alarm" "error-importing-rfid" {
      alarm_name          = "error-rfid-data-import-alarm"
      metric_name         = "error-rfid-data-import-metric"
      threshold           = "0"
      statistic           = "Sum"
      comparison_operator = "GreaterThanThreshold"
      datapoints_to_alarm = "1"
      evaluation_periods  = "1"
      period              = "60"
      namespace           = "LogMetrics"
    
      alarm_actions = [aws_sns_topic.alarm.arn]
    }