You cannot mix EC2-based capacity providers with Fargate capacity providers on the same cluster. If you need Fargate, create a separate cluster.
Prerequisites
Before attaching an ASG as a capacity provider, you need an Auto Scaling Group. Theterraform-aws-autoscaling module is the recommended way to create one.
Key requirements for ASGs used with ECS:
- The EC2 instances must run the ECS-optimized Amazon Linux 2023 AMI (or equivalent). Retrieve the latest AMI ID from SSM:
- Instances must have the
AmazonEC2ContainerServiceforEC2RoleIAM policy attached. - User data must register the instance with the correct ECS cluster:
- The ASG must have
protect_from_scale_in = truewhen usingmanaged_termination_protection = "ENABLED". - Tag the ASG with
AmazonECSManaged = trueto avoid provider issues:
Setting up the Auto Scaling Groups
Theec2-autoscaling example creates two ASGs — one for on-demand instances and one for Spot:
Attaching ASGs as capacity providers
Once the ASGs exist, reference their ARNs in thecapacity_providers input of the cluster module. Each entry in the map creates one ECS capacity provider resource.
Managed scaling configuration
Managed scaling allows ECS to automatically adjust the size of the ASG based on the number of tasks waiting to be placed.Managed draining and termination protection
Managed draining (managed_draining = "ENABLED") instructs ECS to automatically drain tasks from container instances before the ASG terminates them. This ensures graceful task shutdown during scale-in events.
Managed termination protection (managed_termination_protection = "ENABLED") prevents the ASG from terminating instances that still have running ECS tasks. ECS removes the scale-in protection only after tasks have been safely moved.
To disable managed draining (useful for testing or when using custom draining logic):
Deploying a service onto EC2 capacity
Services that target EC2 capacity providers must setrequires_compatibilities = ["EC2"] and reference the capacity provider by name:

