Terraform Auto Scaling Groups for AWS: Provisioning, Policies, and Production Patterns

Auto Scaling Groups let you run a collection of EC2 instances with the same configuration and manage their count manually or dynamically to lower operating costs. Terraform provisions and manages the Auto Scaling group definition, but it does not manage the underlying instances directly because every scaling action would introduce state drift. Lifecycle arguments are used to avoid drift or accidental changes when capacity changes outside of Terraform.

The core tutorial workflow uses Terraform to provision and manage an Auto Scaling group, launch an ASG with traffic managed by a load balancer, and define a scaling policy to automatically modify the number of instances running in the group. Learning how to use lifecycle arguments is central to avoiding unwanted scaling of the ASG.

What Auto Scaling Groups Mean in AWS and Terraform

An Auto Scaling Group without scaling policies is just a fixed-size group of instances. The real power comes from policies that automatically adjust capacity based on metrics, schedules, or predictions. Terraform supports all the scaling policy types AWS offers, and getting the right combination can make the difference between a responsive application and one that crumbles under load.

Autoscaling is a dynamic and automated computing feature intended to adapt to fluctuating jobs. When running a web application where client count varies over the day, autoscaling permits infrastructure to change the quantity of resources such as virtual machines or instances in response to demand naturally. When traffic increases, autoscaling adds more resources to efficiently handle the load. During low demand, it reduces the number of resources to save costs.

In modern cloud computing environments, the ability to dynamically scale resources in light of changing interests is essential for keeping up with execution, accessibility, and cost-effectiveness. Autoscaling and Autoscaling Groups are key parts that enable this unique scaling functionality in cloud infrastructures. With the assistance of Terraform, an Infrastructure as Code tool, provisioning and overseeing Autoscaling Groups becomes smoothed out and automated.

Why Terraform Lifecycle Matters for Dynamic ASGs

Since ASGs are dynamic, Terraform does not manage the underlying instances directly because every scaling action would introduce state drift. You can use Terraform lifecycle arguments to avoid drift or accidental changes.

The tutorial assumes familiarity with the standard Terraform workflow and focuses on how Terraform configuration supports the dynamic aspects of the resource. The configuration supports launch templates, desired capacity, min and max size, health checks, termination policies, and VPC zone identifiers.

Core Terminology and Design Principles

Autoscaling is a dynamic and automated distributed computing feature designed to adjust to fluctuating jobs.

Launch templates replace launch configurations for new and existing Auto Scaling groups to ensure access to the latest features and instance types. As of January 1, 2023, new instance types are no longer supported in launch configurations, and AWS recommends migrating to launch templates for all new and existing Auto Scaling groups.

Infrastructure as Code has become essential for managing cloud resources, and Terraform is one of the most popular tools for this purpose. Terraform allows you to define AWS resources like Auto Scaling Groups in declarative configuration files, enabling consistent, repeatable deployments across environments while maintaining version control.

Launch Templates vs Launch Configurations

The example below defines a launch template and then uses this in the autoscaling group resource block.

provider "aws" { region = "us-west-2" } resource "aws_launch_template" "template" { name_prefix = "test" image_id = "ami-1a2b3c" instance_type = "t2.micro" security_groups = ["sg-12345678"] }

The launch configuration block specifies a name prefix to use for all versions of this launch configuration.

Using launch templates instead of launch configurations is recommended.

Defining an Auto Scaling Group with Terraform

Determine the scaling policies you want to apply to the Auto Scaling group.

How to create an AWS Auto Scaling Group in Terraform:

resource "aws_autoscaling_group" "autoscale" { name = "test-autoscaling-group" availability_zones = ["us-west-2"] desired_capacity = 3 max_size = 6 min_size = 3 health_check_type = "EC2" termination_policies = ["OldestInstance"] vpc_zone_identifier = ["subnet-12345678"] launch_template { id = aws_launch_template.template.id version = "$Latest" } }

Key arguments used in the definition:

Argument Example Value Purpose
name test-autoscaling-group Identifier for the ASG
desired_capacity 3 Target number of instances
min_size 3 Lower bound for scaling
max_size 6 Upper bound for scaling
healthchecktype EC2 Health check source
termination_policies OldestInstance Instance termination order
vpczoneidentifier subnet-12345678 Subnets for instance launch
launch_template.id awslaunchtemplate.template.id Template reference
launch_template.version $Latest Template version

The launch template resource defines imageid, instancetype, and security_groups. The ASG references the template by id and version.

Scaling Policies and Policy Types

Simple scaling is the oldest and most straightforward type. It adds or removes a fixed number of instances when a CloudWatch alarm fires.

Terraform supports all the scaling policy types AWS offers. The main types you can configure with Terraform are:

  • Simple Scaling Policies
  • Step Scaling Policies
  • Target Tracking Scaling Policies
  • Scheduled Scaling Policies
  • Predictive Scaling Policies

A comparison of scaling behavior:

Policy Type Trigger Adjustment
Simple Scaling CloudWatch alarm Fixed number of instances
Step Scaling CloudWatch alarm Multiple adjustments based on alarm breach
Target Tracking Metric target Automatic adjustment to maintain target
Scheduled Cron schedule Predefined capacity at time
Predictive Forecast Proactive capacity changes

Instance Refresh and Lifecycle Hooks

The Terraform AWS Autoscaling module can create Auto Scaling resources on AWS with advanced capabilities.

Capabilities include:

  • Autoscaling group with launch template - either created by the module or utilizing an existing launch template
  • Autoscaling group utilizing mixed instances policy
  • Ability to configure autoscaling groups to set instance refresh configuration and add lifecycle hooks
  • Ability to create an autoscaling group that respects desired_capacity or one that ignores to allow for scaling without conflicting Terraform diffs
  • IAM role and instance profile creation

Module example:

module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "example-asg" min_size = 0 max_size = 1 desired_capacity = 1 wait_for_capacity_timeout = 0 health_check_type = "EC2" vpc_zone_identifier = ["subnet-1235678", "subnet-87654321"] initial_lifecycle_hooks = [ { name = "ExampleStartupLifeCycleHook" default_result = "CONTINUE" heartbeat_timeout = 60 lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING" notification_metadata = jsonencode({ "hello" = "world" }) }, { name = "ExampleTerminationLifeCycleHook" default_result = "CONTINUE" heartbeat_timeout = 180 lifecycle_transition = "autoscaling:EC2_INSTANCE_TERMINATING" notification_metadata = jsonencode({ "goodbye" = "world" }) } ] instance_refresh = { strategy = "Rolling" preferences = { checkpoint_delay = 600 checkpoint_percentages = [35, 70, 100] instance_warmup = 300 min_healthy_percentage = 50 max_healthy_percentage = 100 } triggers = ["tag"] } }

Instance refresh allows controlled replacement of instances with new launch template versions. Lifecycle hooks let you pause scaling events for custom actions during launch or termination.

Best Practices and Operational Considerations

Terraform provides several advantages for managing ASGs. For larger organizations or complex infrastructure, Terragrunt serves as an excellent thin wrapper around Terraform that provides additional benefits.

Key considerations when defining an ASG with Terraform:

  • Define a launch template and autoscaling group block separately
  • Use availability zones and vpczoneidentifier to control placement
  • Set healthchecktype to EC2 or ELB as appropriate
  • Configure termination_policies for predictable scale-in behavior
  • Use lifecycle { ignorechanges = [desiredcapacity] } to avoid Terraform fighting autoscaling actions
  • Define scaling policies after the ASG exists
  • Use instance refresh with rolling strategy and warmup periods
  • Configure lifecycle hooks for startup and termination validation

Conclusion

Auto Scaling Groups paired with Terraform provide a foundation for self-healing, efficient infrastructure that adapts to business needs. By implementing Auto Scaling Groups with Terraform, you gain declarative configuration, version control, repeatable deployments, and integration with scaling policies and instance refresh.

The principles remain relevant: define your infrastructure as code, automate everywhere possible, and let the cloud handle the heavy lifting of scaling and availability. Whether scaling to handle millions of users or ensuring an application never goes down at 3 AM, AWS Auto Scaling Groups paired with Terraform provide the foundation you need.

As the cloud continues to evolve, the core patterns covered here remain relevant: define infrastructure as code, automate everywhere possible, and let the cloud handle scaling and availability.

Sources

  1. HashiCorp Developer
  2. OneUptime Blog
  3. GeeksforGeeks DevOps
  4. Spacelift Blog
  5. LinkedIn Pulse
  6. Terraform AWS Modules GitHub

Related Posts