Creates a target tracking scaling policy using AWS metric math to dynamically adjust the AutoScaling group size based on queue and instance metrics.

Terraform Template

resource "aws_autoscaling_policy" "example" {
  autoscaling_group_name = "my-test-asg"
  name = "foo"
  policy_type = "TargetTrackingScaling"

  target_tracking_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 group size (the number of InService instances)"

        metric_stat {

          metric {

            dimensions {
              name = "AutoScalingGroupName"
              value = "my-asg"
            }
            metric_name = "GroupInServiceInstances"
            namespace = "AWS/AutoScaling"
          }
          stat = "Average"
        }
        return_data = false
      }

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