How to configure EC2 Auto Scaling groups on AWS
Set up an EC2 Auto Scaling group with a launch template, load balancer integration, target tracking, and ELB health checks for elastic, self-healing capacity.
An EC2 Auto Scaling group (ASG) keeps a fleet of instances at the right size automatically. It launches and terminates instances from a launch template, replaces unhealthy ones, and scales on metrics like CPU. Paired with a load balancer, it delivers elastic, self-healing capacity.
Prerequisites
- An AWS account, a VPC with subnets across AZs, and Terraform.
Steps
1. Create a launch template
The template defines the AMI, instance type, security groups, and user data:
resource "aws_launch_template" "web" {
image_id = "ami-0abcd1234"
instance_type = "t3.micro"
user_data = base64encode(file("bootstrap.sh"))
}
2. Define the ASG
resource "aws_autoscaling_group" "web" {
min_size = 2
max_size = 6
desired_capacity = 2
vpc_zone_identifier = [var.subnet_a, var.subnet_b]
launch_template { id = aws_launch_template.web.id; version = "$Latest" }
}
Span multiple subnets so a single AZ failure does not take you down.
3. Attach a load balancer
Attach an Application Load Balancer target group so new instances automatically receive traffic and draining instances stop receiving it.
4. Add a scaling policy
Target tracking is the simplest, keep average CPU near 50%:
resource "aws_autoscaling_policy" "cpu" {
autoscaling_group_name = aws_autoscaling_group.web.name
policy_type = "TargetTrackingScaling"
target_tracking_configuration {
predefined_metric_specification { predefined_metric_type = "ASGAverageCPUUtilization" }
target_value = 50
}
}
5. Configure health checks
Use ELB health checks so the ASG replaces instances the load balancer marks unhealthy, not just those that fail EC2 status checks.
6. Test scaling
Generate load against the endpoint and watch the desired capacity rise; remove load and watch it fall after the cooldown.
Verification
In the EC2 console, confirm the ASG holds the desired count and instances are spread across AZs. Terminate an instance manually and confirm the ASG launches a replacement. Drive CPU up and confirm a scale-out activity in the group's history.
Next Steps
Add warm pools for faster scale-out, use mixed instance policies with Spot for cost savings, and add scheduled scaling for predictable daily peaks.
Prerequisites
- AWS account
- A VPC with subnets
- Terraform installed
Steps
- 1Create a launch template
- 2Define the ASG
- 3Attach a load balancer
- 4Add a scaling policy
- 5Configure health checks
- 6Test scaling