Auto Scaling

The resource type “aws_autoscaling_group” creates an AutoScaling Group.

You must specify either launch_configuration, launch_template, or mixed_instances_policy.

The resource types “aws_launch_template” and “aws_launch_configuration” create a new Launch template and Launch configuration.

To create a Launch configuration,

  • image_id
  • instance_type  are mandatory arguments.

AutoScaling Group With Launch Template

resource "aws_launch_template" "test_l_tmpl" {
  name_prefix = "test_tmpl"
  image_id = "ami-1a2b3c"
  instance_type = "t2.micro"
  block_device_mappings {
    device_name = "/dev/sda1"
    ebs {
      volume_size = 20
    }
  }
}

resource "aws_autoscaling_group" "test_ag" {
  availability_zones = ["us-east-1a"]
  desired_capacity = 2
  max_size = 3
  min_size = 1
  launch_template = {
    id = "${aws_launch_template.test_l_tmpl.id}"
  }
}

AutoScaling Group With Launch Configuration

resource "aws_launch_configuration" "test_launch_configuration" {
  name = "test-launch-configuration"
  image_id = "${lookup(var.ami, var.region)}"
  instance_type = "t2.micro"
  iam_instance_profile = "${aws_iam_instance_profile.ecs_instance_profile.id}"

  root_block_device {
    volume_type = "standard"
    volume_size = 30
    delete_on_termination = true
  }
  lifecycle {
    create_before_destroy = true
  }
  security_groups = ["${aws_security_group.ecs_security_group.id}"]
  associate_public_ip_address = "true"
  key_name = "${var.key_pair_name}"
}
resource "aws_autoscaling_group" "test_autoscaling_group" {
  name = "test-autoscaling-group"
  max_size = "${var.max_instance_size}"
  min_size = "${var.min_instance_size}"
  desired_capacity = "${var.desired_capacity}"
  vpc_zone_identifier = ["${aws_subnet.test_subnets.*.id}"]
  launch_configuration = "${aws_launch_configuration.test_launch_configuration.name}"
  health_check_type = "ELB"
}

AutoScaling Group With Mixed Instances Policy

resource "aws_launch_template" "test_tmplt" {
  name_prefix = "test_template"
  image_id = "${lookup(var.ami, var.region)}"
  instance_type = "t2.large"
}

resource "aws_autoscaling_group" "example" {
  availability_zones = ["us-east-1a"]
  desired_capacity = 2
  max_size = 3
  min_size = 1
  mixed_instances_policy {
    launch_template {
      launch_template_specification {
        launch_template_id = "${aws_launch_template.test_tmplt.id}"
      }
      override {
        instance_type = "c4.large"
      }
      override {
        instance_type = "c3.large"
      }
    }
  }
}