0
votes

We have a use case where we wanted to scale ECS services. There are about 10 services. I don't want to add scaling code in each of the service modules. Also, I don't want to create a module for this and call them for each service in root module main.tf.

In the below code there are only a few variables which would change for the example service name, target group arn etc.

resource "aws_appautoscaling_target" "ecs_target" {
  max_capacity       = "${var.max_capacity}"
  min_capacity       = "${var.min_capacity}"
  resource_id        = "service/${var.cluster}/${aws_ecs_service.rc.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"
}

resource "aws_appautoscaling_policy" "ecs_policy" {
  #count              = "${var.auto_scaling_enabled}"
  name               = "rc-ecs-auto-scale"
  policy_type        = "TargetTrackingScaling"
  resource_id        = "service/cluster/${aws_ecs_service.rc.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  service_namespace  = "ecs"

  target_tracking_scaling_policy_configuration {
    predefined_metric_specification {
      predefined_metric_type = "ALBRequestCountPerTarget"

      resource_label = "${var.alb_arn_suffix}/${aws_alb_target_group.rc.arn_suffix}"
    }

    target_value       = "${var.threshold_value_to_scale}"
    scale_in_cooldown  = "${var.scale_in_cooldown}"
    scale_out_cooldown = "${var.scale_out_cooldown}"
  }

  depends_on = ["aws_appautoscaling_target.ecs_target"]
}

What would be the best way to achieve this?

1

1 Answers

0
votes

You can accomplish it with a module or without modules but with a module is more elegant.

1) Create a module with the above resources with a count of 10 for each resource above so you can loop through them.

2) Call the module with with an array of 10 values for each parameter for each service.

module "services" {
  service_names = []
  capacity = []
  ...
}