Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom metric in AWS cloudwatch using metric math expressions in terraform

I have an ECS cluster and I want to enable application autoscaling using TargetTrackingScaling policy type with a custom metric. I was looking for a way to create this custom metric with terraform but I couldn't find the appropriate resource for this.

Alternatively I tried terraform's aws_cloudwatch_metric_alarm resource and was able to get the alarm created for the custom metric I wanted to create. But I couldn't find the custom metric created anywhere in the AWS cloudwatch console.

Below is the resource that I used to create the alarm.

Is there any way by which I can create a custom metric using the following resource, for the metric query with id "customMetric"? If not can someone please point me to the right terraform resource that I can use here?

resource "aws_cloudwatch_metric_alarm" "foobar" {
  alarm_name                = "autoscaling-test"
  comparison_operator       = "GreaterThanOrEqualToThreshold"
  evaluation_periods        = "2"
  threshold                 = "1"
  alarm_description         = "Alarm to check if the autoscaling works with multiple metrics"
  insufficient_data_actions = []

  metric_query {
    id          = "customMetric"
    expression  = "IF(m1 > 70, 1, 0) OR IF(m2 > 75, 1, 0)"
    label       = "custom metric"
    return_data = "true"
  }

  metric_query {
    id = "m1"

    metric {
      metric_name = "CPUUtilization"
      namespace   = "AWS/ECS"
      period      = "120"
      stat        = "Average"
      unit        = "Percent"

      dimensions = {
        ClusterName = "<clusterName>"
        ServiceName = "<serviceName>"
      }
    }
  }

  metric_query {
    id = "m2"

    metric {
      metric_name = "MemoryUtilization"
      namespace   = "AWS/ECS"
      period      = "120"
      stat        = "Average"
      unit        = "Percent"

      dimensions = {
        ClusterName = "<clusterName>"
        ServiceName = "<serviceName>"
      }
    }
  }
}
like image 882
Ashay Fernandes Avatar asked Feb 04 '26 11:02

Ashay Fernandes


1 Answers

I ran your terraform code & here's how I found the custom metric label which showed up right away. Go to cloudwatch -> All alarms & click on your autoscaling-test alarm. In the upper right corner of the graph, where there's a button labelled, "View in metrics"... click on that & you should see it there.

Normally when I create a custom metric, I have a custom namespace with it and I can find it when I browse the metrics. These expressions seem to work a little differently in cloudwatch.

like image 111
paulg Avatar answered Feb 06 '26 05:02

paulg