Autoscaling

AWS Autoscaling allows us to automatically add or remove instances when certain thresholds are reached. There are two components that needs to be created in order to setup an autoscaling group in AWS,

  • An AWS launch configuration: This is the component that defines AMIs and regions like configurations.

  • An autoscaling group: This specifies the properties used to scale resources. For example the CPU threshold to be considered.

In this section I will be reusing the set up we used in the previous sections. In addtion to the previous content, I will be craeting a couple of additional resources as follows.

Let's craete a file with the name autoscaling.tf,

resource "aws_launch_configuration" "example-launchconfig" {
  name_prefix     = "example-launchconfig"
  image_id        = var.AMIS[var.AWS_REGION]
  instance_type   = "t2.micro"
  key_name        = aws_key_pair.mykeypair.key_name
  security_groups = [aws_security_group.allow-ssh.id]
}

resource "aws_autoscaling_group" "example-autoscaling" {
  name                      = "example-autoscaling"
  vpc_zone_identifier       = [aws_subnet.main-public-1.id, aws_subnet.main-public-2.id]
  launch_configuration      = aws_launch_configuration.example-launchconfig.name
  min_size                  = 1
  max_size                  = 2
  health_check_grace_period = 300
  health_check_type         = "EC2"
  force_delete              = true

  tag {
    key                 = "Name"
    value               = "ec2 instance"
    propagate_at_launch = true
  }
}

In here, I first define the launch configuration. There I specify a name prefix and an ami with some other properties. Next it is the autoscaling group. In there I specify which subnets of the VPC to be used when launching the EC2 instances. Associate it with a launch configuration and specify the minimum and maximum number of instances it could have, and so on.

Then let's create a file with the name autoscalingpolicy.tf,

Generate ssh keys,

Initialize the providers,

Apply the changes,

Don't forget to clean up once experiments are done,

Last updated

Was this helpful?