Labs · DevOps
Lab: Create a Launch Template, an Auto Scaling Group (min 1, desired 2, max 4) and a CPU Target-Tracking Policy with Terraform, Then Terminate a Server and Watch It Come Back
Course: DevOps · Chapter 44: Terraform AWS Guides EC2 RDS S3 Security Groups IAM ALB and Auto Scaling · Lesson: 44.7 How to create a launch template and Auto Scaling group
Lesson 44.7 explains launch templates, group sizes and target tracking; this lab proves self-healing.
Chala mitrano! Ratri 3 vajta server padla tar koN uthNar? Auto Scaling group.
Suppose we are…
Suppose we are on a Netflix-style team before a big series launch. We cannot guess how many servers we need, and at 3 a.m. nobody wants to add them by hand. An Auto Scaling group keeps a minimum number of servers running, replaces broken ones, and adds more when CPU goes up. A launch template is the recipe each new server is built from.
Goal of this lab
By the end you will have:
- An Auto Scaling group with 2 healthy instances.
- A terminated instance replaced automatically.
- Everything destroyed.
What you need
- Terraform 1.6 or newer (
terraform version). - AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (
aws sts get-caller-identityworks). Never use the root user, and never paste access keys into .tf files. - Region Mumbai (
ap-south-1) is used; changeregionif you prefer another. - 40 minutes.
Cost and cleanup
Two t3.micro instances are billed by the hour while the group runs. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.
Part 1: Create the project files
Create the folder:
mkdir asg-guide && cd asg-guideWhat you should see: after the next steps, this layout:
asg-guide/ ├── versions.tf ├── variables.tf ├── main.tf └── outputs.tfCreate
versions.tf:versions.tf
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = var.region }Create
variables.tf:variables.tf
variable "region" { type = string default = "ap-south-1" }Create
main.tf:main.tf
data "aws_ami" "al2023" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-2023.*-x86_64"] } } data "aws_vpc" "default" { default = true } data "aws_subnets" "default" { filter { name = "vpc-id" values = [data.aws_vpc.default.id] } } resource "aws_launch_template" "web" { name_prefix = "guide-web-" image_id = data.aws_ami.al2023.id instance_type = "t3.micro" metadata_options { http_tokens = "required" } user_data = base64encode(<<-EOT #!/bin/bash dnf install -y nginx echo "ASG server $(hostname)" > /usr/share/nginx/html/index.html systemctl enable --now nginx EOT ) } resource "aws_autoscaling_group" "web" { name = "guide-web-asg" min_size = 1 desired_capacity = 2 max_size = 4 vpc_zone_identifier = data.aws_subnets.default.ids health_check_type = "EC2" launch_template { id = aws_launch_template.web.id version = "$Latest" } tag { key = "Name" value = "guide-web-asg" propagate_at_launch = true } } resource "aws_autoscaling_policy" "cpu50" { name = "cpu-50" autoscaling_group_name = aws_autoscaling_group.web.name policy_type = "TargetTrackingScaling" target_tracking_configuration { predefined_metric_specification { predefined_metric_type = "ASGAverageCPUUtilization" } target_value = 50 } }Create
outputs.tf:outputs.tf
output "asg_name" { value = aws_autoscaling_group.web.name }
Part 2: Init, check and plan
Download the AWS provider:
terraform initWhat you should see:
Terraform has been successfully initialized!Format and validate:
terraform fmt terraform validateWhat you should see:
Success! The configuration is valid.Plan and read the counts:
terraform planWhat you should see:
Plan: 3 to add, 0 to change, 0 to destroy.
Part 3: Apply and test
Apply and type
yes:terraform applyCheck both instances are healthy:
aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names guide-web-asg --query "AutoScalingGroups[0].Instances[].[InstanceId,HealthStatus]"What you should see: two instances, both
Healthy.Terminate one instance by hand (use one id from the previous output):
aws ec2 terminate-instances --instance-ids i-0123456789abcdef0Wait 2–4 minutes and read the activity history:
aws autoscaling describe-scaling-activities --auto-scaling-group-name guide-web-asg --max-items 3 --query "Activities[].Description"What you should see:
Terminating EC2 instance ...followed byLaunching a new EC2 instance ..., and again two healthy instances.
Clean up: destroy everything
Delete everything this lab created. Type
yeswhen asked:terraform destroyWhat you should see:
Destroy complete! Resources: 3 destroyed.The group terminates its instances first.
Ravindra Bagale's Tip
Never fix a server inside an Auto Scaling group by hand. Fix the launch template; new instances get the fix, and old ones can be replaced with an instance refresh.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
Error: waiting for Auto Scaling Group (guide-web-asg) capacity satisfied: | Group never reaches desired capacity | Read the scaling activity: aws autoscaling describe-scaling-activities --auto-scaling-group-name guide-web-asg. Usually the instance type is not offered in one subnet zone, or the AMI is wrong. Fix the template and apply again. |
| Terminating instances to save money | The group starts new ones | Set desired capacity to 0 or destroy the group |
Skipping terraform plan | Surprise changes or deletes | Always read the plan counts before apply |
Self-check checklist
0 of 4 done
Try-at-home challenge
Change desired_capacity to 3 in code, apply, and see a third instance start. Then explain why the target-tracking policy may change the number again later.
Samajla ka? The group keeps the count; you keep the template. Aata pudhe jaauya full VPC lab.