SAA-C03 Advanced 45 min

Configure Auto Scaling with ALB

Build a highly available auto-scaling web tier with an ALB, Launch Template, and CloudWatch-triggered scaling policies.

EC2 Auto ScalingApplication Load BalancerLaunch TemplateCloudWatch
Progress: 0 / 5 steps
Step 1
Create Launch Template with User Data

1. EC2 → Launch Templates → Create launch template
2. Name: web-launch-template
3. AMI: Amazon Linux 2023
4. Instance type: t2.micro
5. Key pair: your key pair
6. Security group: Create new:
- HTTP (80) from 0.0.0.0/0
- SSH (22) from My IP
7. Advanced → User data: paste script below

bash
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
cat > /var/www/html/index.html << HTML
<h1>Instance: $INSTANCE_ID</h1>
<p>AZ: $AZ</p>
HTML
Tip: User data runs as root on first boot. It self-configures the instance — no manual SSH needed.
Step 2
Create Application Load Balancer

1. EC2 → Load Balancers → Create → Application Load Balancer
2. Name: web-alb, Scheme: Internet-facing
3. VPC: default or your VPC, Subnets: select 2 public subnets in different AZs
4. Security group: Create new → allow HTTP (80) from 0.0.0.0/0
5. Target group: Create new → Instances, HTTP, port 80, health: /
6. Create

Tip: ALB must span ≥2 AZs. Health check path "/" must return HTTP 200 for instances to be considered healthy.
Step 3
Create Auto Scaling Group

1. EC2 → Auto Scaling Groups → Create
2. Name: web-asg, Launch template: web-launch-template
3. VPC: your VPC, Subnets: both public subnets
4. Load balancing: Attach to existing → select web-alb target group
5. Health checks: Enable ELB health checks
6. Group size: Min=2, Desired=2, Max=4
7. Scaling policy: Target Tracking, CPU utilization, Target=50%
8. Create

Tip: Min=2 across 2 AZs ensures 1 instance per AZ survives an AZ failure. The ALB routes away from unhealthy instances.
Step 4
Test the Setup

1. Get ALB DNS name from Load Balancers → copy DNS name
2. Open in browser → you see instance ID + AZ
3. Refresh multiple times → instance ID may change (load balancing!)
4. Simulate high CPU to trigger scale-out:

bash
# SSH into one instance:
# Replace IP with your instance public IP
ssh -i my-key-pair.pem ec2-user@INSTANCE_IP

# Install and run stress test:
sudo yum install -y stress
stress --cpu 2 --timeout 300 &

# Watch in console: EC2 → Auto Scaling → Activity
Tip: CloudWatch alarm triggers scale-out when avg CPU > 50% for 3 minutes. New instances launch from Launch Template.
Step 5
Clean Up

1. Auto Scaling Group → Delete (this terminates all instances)
2. Load Balancer → Delete
3. Target Group → Delete
4. Launch Template → Delete
5. Security groups created for this lab → Delete

Tip: Always delete ASG first — it will automatically terminate the EC2 instances it manages.