EC2 Auto Scaling Based on CPU Usage


Here’s an example Terraform configuration for automatically scaling an EC2 cluster based on CPU load:

provider "aws" {
  region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

resource "aws_autoscaling_group" "example" {
  name_prefix = "example-asg-"
  vpc_zone_identifier = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef1"]
  launch_template = {
    id = aws_launch_template.example.id
  }
  min_size = 1
  max_size = 5

  tag {
    key                 = "Name"
    value               = "example-asg"
    propagate_at_launch = true
  }

  metric_collection {
    granularity = "1Minute"
  }

  scaling_policy {
    name                 = "cpu_scale_up_policy"
    adjustment_type      = "ChangeInCapacity"
    scaling_adjustment   = 1
    cool_down_period     = 300
    evaluation_periods   = "2"
    policy_type          = "TargetTrackingScaling"
    target_tracking_configuration {
      predefined_metric_specification {
        predefined_metric_type = "ECSSystemCPUUtilization"
      }
      target_value = 80
    }
  }

  scaling_policy {
    name                 = "cpu_scale_down_policy"
    adjustment_type      = "ChangeInCapacity"
    scaling_adjustment   = -1
    cool_down_period     = 300
    evaluation_periods   = "2"
    policy_type          = "TargetTrackingScaling"
    target_tracking_configuration {
      predefined_metric_specification {
        predefined_metric_type = "ECSSystemCPUUtilization"
      }
      target_value = 40
    }
  }
}

resource "aws_launch_template" "example" {
  image_id      = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  lifecycle {
    create_before_destroy = true
  }

  tag {
    key                 = "Name"
    value               = "example-launch-template"
    propagate_at_launch = true
  }
}

This Terraform configuration uses the AWS provider to create an EC2 Auto Scaling Group (ASG) with a minimum size of 1 instance and a maximum size of 5 instances. The ASG uses a launch template that specifies the Ubuntu 20.04 AMI and a t2.micro instance type.

The ASG is set up with two scaling policies, one for scaling up and one for scaling down, both of which use the ECSSystemCPUUtilization metric and target tracking scaling. The scale up policy

Zak's AI.Assist

Session only - not saved