Skip to main content
This example creates an ECS cluster with an EC2 Auto Scaling Group (ASG) capacity provider using the standalone cluster and service sub-modules.

What is created

  • ECS cluster with an EC2 ASG capacity provider (managed scaling enabled)
  • EC2 Auto Scaling Group with ECS-optimized AMI
  • ECS service configured for EC2 launch type
  • Application Load Balancer
  • VPC with private/public subnets
  • IAM roles for EC2 instances

Prerequisites

You must create an Auto Scaling Group before attaching it as a capacity provider. This example uses the terraform-aws-autoscaling module for that purpose.

Code

module "ecs_cluster" {
  source = "terraform-aws-modules/ecs/aws//modules/cluster"

  name = local.name

  default_capacity_provider_strategy = {
    one = { weight = 60, base = 20 }
    two = { weight = 40 }
  }

  capacity_providers = {
    one = {
      auto_scaling_group_provider = {
        auto_scaling_group_arn         = module.autoscaling["one"].autoscaling_group_arn
        managed_draining               = "ENABLED"
        managed_termination_protection = "ENABLED"

        managed_scaling = {
          maximum_scaling_step_size = 5
          minimum_scaling_step_size = 1
          status                    = "ENABLED"
          target_capacity           = 60
        }
      }
    }
    two = {
      auto_scaling_group_provider = {
        auto_scaling_group_arn         = module.autoscaling["two"].autoscaling_group_arn
        managed_draining               = "ENABLED"
        managed_termination_protection = "ENABLED"

        managed_scaling = {
          maximum_scaling_step_size = 15
          minimum_scaling_step_size = 5
          status                    = "ENABLED"
          target_capacity           = 90
        }
      }
    }
  }

  tags = local.tags
}

Key highlights

  • AmazonECSManaged = true tag: The ASG must have this tag for ECS managed scaling to work.
  • protect_from_scale_in = true: Required when managed_termination_protection = "ENABLED" — prevents AWS from terminating instances before ECS drains tasks.
  • ignore_desired_capacity_changes = true: Prevents Terraform from resetting ASG desired capacity that ECS manages.
  • Multiple ASGs: The example uses two ASGs with different instance types and capacity provider weights.

EC2 Autoscaling Guide

Detailed guide for EC2 Auto Scaling capacity providers.

Managed Instances Example

Simpler fleet management without managing ASGs.

Build docs developers (and LLMs) love