Home AWSAmazon EC2 Auto Scaling Groups: A Hands-On Beginner’s Guide

Amazon EC2 Auto Scaling Groups: A Hands-On Beginner’s Guide

by Knowledge Base Linux
Amazon EC2 Auto Scaling Groups — Amazon EC2 Auto Scaling Groups: A Hands-On Beginner's Guide

Manually adding EC2 instances when traffic spikes — and remembering to remove them when traffic dies down — is a recipe for both outages and wasted money. An EC2 Auto Scaling group solves this by automatically launching and terminating EC2 instances to match demand, while keeping a minimum number of healthy instances running at all times. In this hands-on guide, you will create a launch template, build an EC2 Auto Scaling group with the AWS CLI, attach a target tracking scaling policy, and configure health checks that actually detect broken instances. This article covers Amazon EC2 Auto Scaling Groups in detail.

Technical illustration of an EC2 Auto Scaling group scaling EC2 instances up and down based on demand

Technical illustration of an EC2 Auto Scaling group adding and removing EC2 instances based on demand

What Is an EC2 Auto Scaling Group? – Amazon EC2 Auto Scaling Groups

An EC2 Auto Scaling group (ASG) is a logical collection of EC2 instances that share the same configuration and scaling rules. You define three numbers: minimum (instances that always run), desired (the current target), and maximum (the hard ceiling). The group continuously compares desired capacity against reality and launches or terminates instances to close the gap.

Three components work together:

  • Launch template — the blueprint: AMI, instance type, key pair, security groups, user data, IAM role, and storage.
  • Scaling policies — the rules that decide when to scale out or in, typically driven by CloudWatch metrics such as average CPU utilization.
  • Health checks — the mechanism that detects unhealthy instances (failed EC2 status checks or failed load balancer health checks) and replaces them automatically.

For a refresher on launching a single instance first, see our guide on how to launch an EC2 instance on AWS.

Prerequisites – Amazon EC2 Auto Scaling Groups

  • An AWS account with IAM permissions for EC2, Auto Scaling, and CloudWatch.
  • AWS CLI v2 installed and configured (aws configure completed).
  • A VPC with at least two public or private subnets in different Availability Zones, and a security group that allows your application traffic.
  • An Application Load Balancer with a target group if you want ELB health checks (recommended).

Step 1: Create a Launch Template for the EC2 Auto Scaling Group

The launch template defines what every instance in the EC2 Auto Scaling group will look like. Start by writing a small user-data script that installs and starts a web server:

#!/bin/bash
dnf update -y
dnf install -y httpd
systemctl enable --now httpd
echo "Served by $(hostname)" > /var/www/html/index.html

User data must be base64-encoded when passed to the AWS CLI. Encode it and store it in a variable:

USER_DATA=$(base64 -w 0 user-data.sh)
echo "$USER_DATA" | cut -c1-60

Now create the launch template, replacing the AMI, key pair, and security group IDs with your own values:

aws ec2 create-launch-template \
  --launch-template-name web-server-template \
  --version-description "v1 initial web server" \
  --launch-template-data "{
    \"ImageId\": \"ami-0abcdef1234567890\",
    \"InstanceType\": \"t3.micro\",
    \"KeyName\": \"my-key-pair\",
    \"SecurityGroupIds\": [\"sg-0123456789abcdef0\"],
    \"IamInstanceProfile\": {\"Name\": \"web-server-role\"},
    \"UserData\": \"$USER_DATA\"
  }"

Verify the template was created and note its default version:

aws ec2 describe-launch-templates \
  --launch-template-names web-server-template \
  --query 'LaunchTemplates[0].{Name:LaunchTemplateName,Default:DefaultVersionNumber}'

Every change to the template creates a new numbered version. When you later reference $Latest or $Default in the Auto Scaling group, new instances pick up the matching version — a clean way to roll out configuration changes.

Step 2: Create the EC2 Auto Scaling Group

With the template in place, create the group across two subnets for high availability. This example registers instances with an existing target group and uses ELB health checks:

aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name web-asg \
  --launch-template "LaunchTemplateName=web-server-template,Version=\$Latest" \
  --min-size 2 \
  --max-size 6 \
  --desired-capacity 2 \
  --vpc-zone-identifier "subnet-0aaa111bbb222ccc3,subnet-0ddd444eee555fff6" \
  --target-group-arns "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-tg/abcdef0123456789" \
  --health-check-type ELB \
  --health-check-grace-period 300 \
  --tags "Key=Name,Value=web-asg-node,PropagateAtLaunch=true"

Check that the group launched its two instances:

aws autoscaling describe-auto-scaling-groups \
  --auto-scaling-group-names web-asg \
  --query 'AutoScalingGroups[0].Instances[].{Id:InstanceId,State:LifecycleState,Health:HealthStatus}'

At this point you have a static fleet of two instances. The next step makes it elastic.

Step 3: Add a Target Tracking Scaling Policy

A target tracking scaling policy is the simplest way to scale an EC2 Auto Scaling group: you pick a metric and a target value, and Auto Scaling adds or removes instances to hold that value. The most common choice is average CPU utilization at 50 percent:

aws autoscaling put-scaling-policy \
  --auto-scaling-group-name web-asg \
  --policy-name cpu-target-tracking \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification": {
      "PredefinedMetricType": "ASGAverageCPUUtilization"
    },
    "TargetValue": 50.0
  }'

How it works in practice: if average CPU across the group stays above 50 percent, the policy launches more instances; when it drops below, instances are terminated — never below min-size, never above max-size. Other predefined metrics include ASGAverageNetworkIn, ASGAverageNetworkOut, and ALBRequestCountPerTarget (requests per instance behind a load balancer, ideal for web workloads).

You can also combine policies: for example, target tracking for day-to-day load plus a scheduled scaling action that raises minimum capacity before a known traffic peak:

aws autoscaling put-scheduled-update-group-action \
  --auto-scaling-group-name web-asg \
  --scheduled-action-name morning-peak \
  --recurrence "0 8 * * *" \
  --min-size 4 \
  --desired-capacity 4

To understand the metrics driving these policies, read our walkthrough of monitoring EC2 with CloudWatch alarms.

Step 4: Configure Health Checks for the EC2 Auto Scaling Group

Scaling is only half the story — the group must also detect and replace broken instances. Two health check types exist:

  • EC2 health checks (default): the instance is replaced if the underlying hardware or system status check fails.
  • ELB health checks: the instance is also replaced if it fails the load balancer’s health check — this catches application-level failures such as a crashed web server that leaves the OS running.

We set --health-check-type ELB at creation. Make sure your target group’s health check path returns HTTP 200 (for example /index.html), and tune the health check grace period so instances are not killed while still booting. Our 300-second grace period gives the user-data script time to finish installing the web server.

To change the grace period later:

aws autoscaling update-auto-scaling-group \
  --auto-scaling-group-name web-asg \
  --health-check-grace-period 600

Test the replacement behavior: terminate one instance manually and watch the group launch a fresh one within a few minutes.

INSTANCE_ID=$(aws autoscaling describe-auto-scaling-groups \
  --auto-scaling-group-names web-asg \
  --query 'AutoScalingGroups[0].Instances[0].InstanceId' --output text)

aws ec2 terminate-instances --instance-ids "$INSTANCE_ID"

aws autoscaling describe-scaling-activities \
  --auto-scaling-group-name web-asg \
  --max-items 3 \
  --query 'Activities[].{Status:StatusCode,Description:Description}'

Troubleshooting Common EC2 Auto Scaling Group Issues

Instances launch but immediately terminate

This is almost always the health check grace period being too short, or the load balancer health check path returning a non-200 response. Check the scaling activities for the exact reason, then either fix the application or extend the grace period.

The group never scales out under load

Confirm the policy exists with aws autoscaling describe-policies --auto-scaling-group-name web-asg, and verify max-size is larger than desired-capacity. Also check that the CloudWatch metric has data — a missing IAM instance profile or blocked CloudWatch endpoint means no metrics, and no metrics means no scaling.

Scaling is slow or flapping

Target tracking policies include a cooldown. For spiky workloads, lower the target value (for example 40 percent CPU) so scaling starts earlier, or add a step scaling policy with a shorter cooldown for aggressive scale-out.

New launch template version not picked up

The group pins the version you specified. If you used an explicit version number instead of $Latest, update the group with aws autoscaling update-auto-scaling-group --launch-template "LaunchTemplateName=web-server-template,Version=\$Latest" and then start an instance refresh to roll the fleet.

Conclusion

You now have a working EC2 Auto Scaling group: a launch template that defines every instance, a group spanning multiple Availability Zones, a target tracking policy that holds CPU near 50 percent, and ELB health checks that replace failed instances automatically. From here, explore instance refresh for zero-downtime template updates, lifecycle hooks for graceful draining, and predictive scaling for workloads with repeating daily patterns. The official Amazon EC2 Auto Scaling user guide is the best next reference.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.