Ravindra BagaleCourses & study guides Track your progress

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

Intermediate40 minTerraform 1.6+ · AWS CLI v2 · An AWS account

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-identity works). Never use the root user, and never paste access keys into .tf files.
  • Region Mumbai (ap-south-1) is used; change region if 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

  1. Create the folder:

    mkdir asg-guide && cd asg-guide
    

    What you should see: after the next steps, this layout:

    asg-guide/
    ├── versions.tf
    ├── variables.tf
    ├── main.tf
    └── outputs.tf
    
  2. Create versions.tf:

    versions.tf

    terraform {
      required_version = ">= 1.6"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 5.0"
        }
      }
    }
    
    provider "aws" {
      region = var.region
    }
    
  3. Create variables.tf:

    variables.tf

    variable "region" {
      type    = string
      default = "ap-south-1"
    }
    
  4. 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
      }
    }
    
  5. Create outputs.tf:

    outputs.tf

    output "asg_name" {
      value = aws_autoscaling_group.web.name
    }
    

Part 2: Init, check and plan

  1. Download the AWS provider:

    terraform init
    

    What you should see: Terraform has been successfully initialized!

  2. Format and validate:

    terraform fmt
    terraform validate
    

    What you should see: Success! The configuration is valid.

  3. Plan and read the counts:

    terraform plan
    

    What you should see: Plan: 3 to add, 0 to change, 0 to destroy.

Part 3: Apply and test

  1. Apply and type yes:

    terraform apply
    
  2. Check 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.

  3. Terminate one instance by hand (use one id from the previous output):

    aws ec2 terminate-instances --instance-ids i-0123456789abcdef0
    
  4. Wait 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 by Launching a new EC2 instance ..., and again two healthy instances.

Clean up: destroy everything

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy
    

    What 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

MistakeWhat happensFix
Error: waiting for Auto Scaling Group (guide-web-asg) capacity satisfied:Group never reaches desired capacityRead 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 moneyThe group starts new onesSet desired capacity to 0 or destroy the group
Skipping terraform planSurprise changes or deletesAlways 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.