title: How to create custom metric in AWS cloudwatch using metric math expressions in terraform
body: <p>I have an ECS cluster and I want to enable application autoscaling using <strong>TargetTrackingScaling</strong> 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.</p>
  <p>Alternatively I tried terraform's <strong>aws_cloudwatch_metric_alarm</strong> 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.</p>
  <p>Below is the resource that I used to create the alarm.</p>
  <p>Is there any way by which I can create a custom metric using the following resource, for the metric query with id &quot;<strong>customMetric</strong>&quot;? If not can someone please point me to the right terraform resource that I can use here?</p>
  <pre><code>resource &quot;aws_cloudwatch_metric_alarm&quot; &quot;foobar&quot; {
    alarm_name                = &quot;autoscaling-test&quot;
    comparison_operator       = &quot;GreaterThanOrEqualToThreshold&quot;
    evaluation_periods        = &quot;2&quot;
    threshold                 = &quot;1&quot;
    alarm_description         = &quot;Alarm to check if the autoscaling works with multiple metrics&quot;
    insufficient_data_actions = []
  
    metric_query {
      id          = &quot;customMetric&quot;
      expression  = &quot;IF(m1 &gt; 70, 1, 0) OR IF(m2 &gt; 75, 1, 0)&quot;
      label       = &quot;custom metric&quot;
      return_data = &quot;true&quot;
    }
  
    metric_query {
      id = &quot;m1&quot;
  
      metric {
        metric_name = &quot;CPUUtilization&quot;
        namespace   = &quot;AWS/ECS&quot;
        period      = &quot;120&quot;
        stat        = &quot;Average&quot;
        unit        = &quot;Percent&quot;
  
        dimensions = {
          ClusterName = &quot;&lt;clusterName&gt;&quot;
          ServiceName = &quot;&lt;serviceName&gt;&quot;
        }
      }
    }
  
    metric_query {
      id = &quot;m2&quot;
  
      metric {
        metric_name = &quot;MemoryUtilization&quot;
        namespace   = &quot;AWS/ECS&quot;
        period      = &quot;120&quot;
        stat        = &quot;Average&quot;
        unit        = &quot;Percent&quot;
  
        dimensions = {
          ClusterName = &quot;&lt;clusterName&gt;&quot;
          ServiceName = &quot;&lt;serviceName&gt;&quot;
        }
      }
    }
  }
  </code></pre>