Creates a target tracking scaling policy for an ECS service using custom metric math expressions.

Terraform Template

resource "aws_appautoscaling_policy" "example" {
  name = "foo"
  policy_type = "TargetTrackingScaling"
  resource_id = aws_appautoscaling_target.ecs_target.resource_id
  scalable_dimension = aws_appautoscaling_target.ecs_target.scalable_dimension
  service_namespace = aws_appautoscaling_target.ecs_target.service_namespace

  target_tracking_scaling_policy_configuration {

    customized_metric_specification {

      metrics {
        id = "m1"
        label = "Get the queue size (the number of messages waiting to be processed)"

        metric_stat {

          metric {

            dimensions {
              name = "QueueName"
              value = "my-queue"
            }
            metric_name = "ApproximateNumberOfMessagesVisible"
            namespace = "AWS/SQS"
          }
          stat = "Sum"
        }
        return_data = false
      }

      metrics {
        id = "m2"
        label = "Get the ECS running task count (the number of currently running tasks)"

        metric_stat {

          metric {

            dimensions {
              name = "ClusterName"
              value = "default"
            }

            dimensions {
              name = "ServiceName"
              value = "web-app"
            }
            metric_name = "RunningTaskCount"
            namespace = "ECS/ContainerInsights"
          }
          stat = "Average"
        }
        return_data = false
      }

      metrics {
        expression = "m1 / m2"
        id = "e1"
        label = "Calculate the backlog per instance"
        return_data = true
      }
    }
    target_value = 100
  }
}

resource "aws_appautoscaling_target" "ecs_target" {
  max_capacity = 4
  min_capacity = 1
  resource_id = "service/clusterName/serviceName"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace = "ecs"
}