Fatskills
Practice. Master. Repeat.
Study Guide: TECH **AWS Auto Scaling Groups & Launch Templates: Zero-Fluff, Hands-On Guide**
Source: https://www.fatskills.com/aws-certified-solutions-architect-associate/chapter/tech-aws-auto-scaling-groups-launch-templates-zero-fluff-hands-on-guide

TECH **AWS Auto Scaling Groups & Launch Templates: Zero-Fluff, Hands-On Guide**

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~8 min read

AWS Auto Scaling Groups & Launch Templates: Zero-Fluff, Hands-On Guide

(For AWS Solutions Architect – Associate & Real-World Deployments)


1. What This Is & Why It Matters

You’re a cloud engineer at a startup. Your app runs on EC2 instances, and traffic spikes unpredictably—sometimes 10x during a marketing campaign, then back to normal. If you over-provision, you waste money. If you under-provision, users see "503 Service Unavailable." Auto Scaling Groups (ASGs) and Launch Templates are your solution.


  • Auto Scaling Groups (ASGs) automatically adjust the number of EC2 instances based on demand (CPU, memory, custom metrics, or schedules).
  • Launch Templates define how those instances are configured (AMI, instance type, security groups, user data, etc.).

Why this matters in production:
- Cost savings: Scale down when idle (e.g., dev environments at night).
- High availability: Replace failed instances automatically.
- Resilience: Survive AZ outages by distributing instances across multiple zones.
- Operational sanity: No more manual instance launches or "oops, we forgot to patch this server."

Real-world scenario:
You inherit a monolithic app running on 10 t3.large instances. Traffic doubles overnight, and your boss asks: - "Why are we paying for 10 instances when we only need 3 at 3 AM?" - "Why did the site crash when one instance failed?" - "How do we roll out security patches without downtime?"

This guide solves all three.


2. Core Concepts & Components


? Auto Scaling Group (ASG)

  • Definition: A logical group of EC2 instances that scales in/out based on policies.
  • Production insight: If you don’t set a cooldown period, ASG might launch too many instances during brief spikes (cost explosion).

? Launch Template

  • Definition: A reusable blueprint for launching EC2 instances (AMI, instance type, key pair, security groups, user data, etc.).
  • Production insight: Always version your launch templates. Rolling back to a previous version is faster than debugging a bad AMI.

? Scaling Policies

  • Target Tracking: Automatically adjusts capacity to maintain a target metric (e.g., 50% CPU).
  • Step Scaling: Adds/removes instances in steps (e.g., +2 instances if CPU > 70%).
  • Scheduled Scaling: Scales at specific times (e.g., +10 instances at 9 AM on weekdays).
  • Production insight: Target tracking is simplest, but step scaling gives you finer control for bursty workloads.

? Health Checks

  • EC2 Health Checks: Checks if the instance is running (default).
  • ELB Health Checks: Checks if the app is responding (e.g., HTTP 200 on /health).
  • Production insight: Always use ELB health checks for web apps—EC2 checks won’t catch a crashed app.

? Lifecycle Hooks

  • Definition: Pauses instance launch/termination to run custom actions (e.g., install software, drain connections).
  • Production insight: Useful for stateful apps (e.g., databases) where you need to gracefully shut down before termination.

? Warm Pools

  • Definition: Pre-initialized instances ready to join the ASG (reduces cold-start latency).
  • Production insight: Critical for apps with long boot times (e.g., Java apps with heavy dependencies).

? Termination Policies

  • Default: Oldest instance first (for rolling updates).
  • Newest Instance: Useful for debugging (terminate the most recently launched instance).
  • Closest to Next Billing Hour: Saves money by terminating instances about to incur a new hour of charges.
  • Production insight: Always set a termination policy—default may not fit your use case.

? Mixed Instances Policy

  • Definition: Lets you use multiple instance types in an ASG (e.g., t3.large + t3.xlarge).
  • Production insight: Saves money by using spot instances for fault-tolerant workloads.


3. Step-by-Step: Deploy a Highly Available Web App with ASG + ALB


Prerequisites

  • AWS account with admin IAM permissions.
  • AWS CLI installed (aws --version).
  • A VPC with at least 2 public subnets (for ALB) and 2 private subnets (for ASG).
  • A key pair for SSH access (optional, for debugging).

Step 1: Create a Launch Template

Launch templates replace the older "Launch Configurations." They’re versioned and support more features (e.g., T2/T3 unlimited, Elastic Graphics).


# Create a launch template with user data to install Apache
aws ec2 create-launch-template \
  --launch-template-name web-app-template \
  --launch-template-data '{
"ImageId": "ami-0c55b159cbfafe1f0", # Amazon Linux 2 (us-east-1)
"InstanceType": "t3.micro",
"KeyName": "your-key-pair",
"SecurityGroupIds": ["sg-12345678"], # Replace with your SG ID
"UserData": "IyEvYmluL2Jhc2gKeXVtIGluc3RhbGwgaHR0ZCAteQpzeXN0ZW1jdGwgc3RhcnQgaHR0ZApzeXN0ZW1jdGwgZW5hYmxlIGh0dGQKZWNobyAiSGVsbG8gV29ybGQhIiA+IC92YXIvd3d3L2h0bWwvaW5kZXguaHRtbA==",
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{ "Key": "Name", "Value": "web-app" }]
}] }'

Verify:


aws ec2 describe-launch-templates --launch-template-names web-app-template

Step 2: Create an Auto Scaling Group

Attach the launch template to an ASG with scaling policies.


# Create ASG across 2 AZs with min 2, max 4 instances
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name web-app-asg \
  --launch-template LaunchTemplateName=web-app-template,Version='$Latest' \
  --min-size 2 \
  --max-size 4 \
  --desired-capacity 2 \
  --vpc-zone-identifier "subnet-12345678,subnet-87654321" # Replace with your private subnets \
  --target-group-arns "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-app-tg/1234567890" # Replace with your ALB target group ARN \
  --health-check-type ELB \
  --health-check-grace-period 300

Verify:


aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names web-app-asg

Step 3: Configure Scaling Policies

Add a target tracking policy to scale based on CPU.


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

Verify:


aws autoscaling describe-policies --auto-scaling-group-name web-app-asg

Step 4: Test Scaling

Simulate load to trigger scaling.


# Install stress tool on one instance (SSH into it first)
sudo yum install -y stress
stress --cpu 4 --timeout 600

Check scaling activity:


aws autoscaling describe-scaling-activities --auto-scaling-group-name web-app-asg

Expected output:


"Description": "Launching a new EC2 instance: i-1234567890abcdef0",
"StatusCode": "InProgress"

Step 5: Clean Up

# Delete ASG (instances will terminate)
aws autoscaling delete-auto-scaling-group --auto-scaling-group-name web-app-asg --force-delete

# Delete launch template
aws ec2 delete-launch-template --launch-template-name web-app-template


4. ? Production-Ready Best Practices


Security

  • Least privilege IAM roles: Attach an IAM role to the launch template (not hardcoded credentials).
  • Security groups: Restrict inbound traffic to the ALB only (no public IPs for ASG instances).
  • Secrets: Use AWS Secrets Manager or Parameter Store for DB credentials (not user data).

Cost Optimization

  • Spot instances: Use a mixed instances policy for fault-tolerant workloads.
    bash --mixed-instances-policy '{
    "LaunchTemplate": {
    "LaunchTemplateSpecification": { "LaunchTemplateName": "web-app-template" },
    "Overrides": [
    { "InstanceType": "t3.micro" },
    { "InstanceType": "t3.small" }
    ]
    },
    "InstancesDistribution": {
    "OnDemandPercentageAboveBaseCapacity": 20,
    "SpotAllocationStrategy": "capacity-optimized"
    } }'
  • Right-size instances: Use AWS Compute Optimizer to pick the best instance type.
  • Scheduled scaling: Scale down dev environments at night.

Reliability & Maintainability

  • Tag everything: Use Name, Environment, Owner tags for cost allocation and automation.
  • Version launch templates: Always specify a version (e.g., Version='$Latest' or Version='2').
  • Rolling updates: Use ASG’s UpdatePolicy in CloudFormation to avoid downtime.
    yaml UpdatePolicy:
    AutoScalingRollingUpdate:
    MinInstancesInService: 1
    MaxBatchSize: 1

Observability

  • CloudWatch alarms: Monitor CPUUtilization, UnHealthyHostCount, and GroupDesiredCapacity.
  • Logs: Stream EC2 logs to CloudWatch Logs.
  • Custom metrics: Publish app-specific metrics (e.g., RequestsPerSecond) for scaling.


5. ⚠️ Common Mistakes & Traps

Mistake Symptom Fix/Prevention
No health checks ASG keeps unhealthy instances running. Always use ELB health checks for web apps.
Too short cooldown ASG launches too many instances during brief spikes. Set cooldown to at least 5 minutes.
No termination policy ASG terminates the wrong instance (e.g., the one with the most data). Set OldestInstance or NewestInstance explicitly.
Public IPs for ASG instances Instances are exposed to the internet. Use private subnets + NAT gateway.
No warm pool Cold starts cause latency spikes. Use warm pools for apps with long boot times.


6. ? Exam/Certification Focus


Typical Question Patterns

  1. Scenario: "Your ASG is scaling too aggressively. What’s the fix?"
  2. Answer: Increase the cooldown period or use step scaling instead of target tracking.

  3. Scenario: "You need to update your ASG with a new AMI without downtime."

  4. Answer: Create a new launch template version, then update the ASG with a rolling update policy.

  5. Trap Distinction:

  6. Launch Template vs. Launch Configuration:


    • Launch templates are newer, support versioning, and work with spot instances.
    • Launch configurations are legacy (don’t use them in new deployments).
  7. Scenario: "Your app is stateful. How do you gracefully terminate instances?"

  8. Answer: Use lifecycle hooks to drain connections before termination.

7. ? Hands-On Challenge

Challenge:
Create an ASG that scales between 1 and 3 instances based on a custom CloudWatch metric (RequestCountPerTarget). Use a launch template with a t3.micro instance and a user data script that installs Nginx.

Solution:


# 1. Create launch template
aws ec2 create-launch-template \
  --launch-template-name nginx-template \
  --launch-template-data '{
"ImageId": "ami-0c55b159cbfafe1f0",
"InstanceType": "t3.micro",
"UserData": "IyEvYmluL2Jhc2gKeXVtIGluc3RhbGwgLXkgbmdpbngKc3lzdGVtY3RsIHN0YXJ0IG5naW54CnN5c3RlbWN0bCBlbmFibGUgbmdpbng=",
"TagSpecifications": [{
"ResourceType": "instance",
"Tags": [{ "Key": "Name", "Value": "nginx" }]
}] }' # 2. Create ASG aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name nginx-asg \ --launch-template LaunchTemplateName=nginx-template,Version='$Latest' \ --min-size 1 \ --max-size 3 \ --desired-capacity 1 \ --vpc-zone-identifier "subnet-12345678,subnet-87654321" # 3. Create scaling policy aws autoscaling put-scaling-policy \ --auto-scaling-group-name nginx-asg \ --policy-name request-scaling \ --policy-type TargetTrackingScaling \ --target-tracking-configuration '{
"CustomizedMetricSpecification": {
"MetricName": "RequestCountPerTarget",
"Namespace": "AWS/ApplicationELB",
"Statistic": "Sum",
"Unit": "Count"
},
"TargetValue": 1000.0 }'

Why it works:
- The ASG scales based on RequestCountPerTarget (a metric published by ALB).
- Nginx is installed via user data, so new instances are ready immediately.


8. ? Rapid-Reference Crib Sheet

Command/Concept Key Details
aws autoscaling create-auto-scaling-group --health-check-type ELB (for web apps)
aws autoscaling put-scaling-policy --policy-type TargetTrackingScaling (simplest)
Launch Template vs. Launch Configuration ⚠️ Always use launch templates (versioned, supports spot).
Default cooldown 300 seconds (5 minutes)
Termination policy ⚠️ Default is OldestInstance (may not be optimal).
Warm pools Reduce cold-start latency for apps with long boot times.
Mixed instances policy Use spot + on-demand for cost savings.
Lifecycle hooks Pause instance launch/termination for custom actions.


9. ? Where to Go Next

  1. AWS Auto Scaling Documentation
  2. Launch Template Best Practices
  3. AWS Well-Architected Framework: Auto Scaling
  4. AWS Compute Optimizer (for right-sizing instances)


ADVERTISEMENT