A step-by-step guide for AWS EC2 provisioning using Terraform: EC2 Auto scaling using Terraform for high availability and resource optimization— Part 9

Joel Wembo
5 min readJun 22, 2024

--

Amazon EC2 Auto Scaling using infrastructure as code terraform helps you maintain application availability and lets you automatically add or remove EC2 instances using scaling policies that you define. Dynamic or predictive scaling policies let you add or remove EC2 instance capacity to service established or real-time demand patterns. The fleet management features of Amazon EC2 Auto Scaling help maintain the health and availability of your fleet.

Terraform enables efficient management of EC2 instances with autoscaling capabilities, automating the process of scaling resources in response to demand. By defining configurations in code, users can create an AWS Launch Configuration and an Auto Scaling Group that dynamically adjusts the number of running instances based on specified policies and metrics such as CPU utilization.

This ensures high availability and optimal performance while maintaining cost efficiency. Terraform’s declarative syntax and state management simplify infrastructure provisioning, modification, and versioning, making it a robust tool for scalable cloud deployments.

To enhance readability, this handbook is divided into chapters and split into parts. The first, part, “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, ALB, VPC, and Route53 — Part 1”, and the second part “A step-by-step guide for AWS EC2 provisioning using Terraform: HA, CloudFront, WAF, and SSL Certificate — Part 2”, and “A step-by-step guide for AWS EC2 provisioning using Terraform: Cloud Cost Optimization, AWS EC2 Spot Instances — Part 3”, was covered in a separate article to keep the reading time manageable and ensure focused content. The next part or chapter will be published in the next post, upcoming in a few days, “A step-by-step guide for AWS EC2 provisioning using Terraform: VPC peering, VPN, Site-to-site Connection, tunnels ( multi-Cloud ) — Part 12“ and so much more !!

Creating an EC2 instance with autoscaling in AWS using Terraform involves several steps. Below is the terraform script to help you set up an autoscaling group with EC2 instances running Ubuntu.

create another file autoscaling.tf


resource "aws_launch_configuration" "prodxcloud-launch_config" {
name = "prodxcloud-launch_config"
image_id = var.instance_ami
instance_type = var.instance_type

lifecycle {
create_before_destroy = true
}
}

resource "aws_autoscaling_group" "prodxcloud-autoscaling-group" {
launch_configuration = aws_launch_configuration.prodxcloud-launch_config.id
min_size = 1
max_size = 3
desired_capacity = 2
vpc_zone_identifier = [element(aws_subnet.prodxcloud_public_subnets.*.id, 1),
element(aws_subnet.prodxcloud_public_subnets.*.id, 2)]

tag {
key = "prxcloud"
value = "prodx-instance-1"
propagate_at_launch = true
}
}

resource "aws_autoscaling_policy" "scale_up" {
name = "scale_up"
scaling_adjustment = 1
adjustment_type = "ChangeInCapacity"
cooldown = 300
autoscaling_group_name = aws_autoscaling_group.prodxcloud-autoscaling-group.name
}

resource "aws_autoscaling_policy" "scale_down" {
name = "scale_down"
scaling_adjustment = -1
adjustment_type = "ChangeInCapacity"
cooldown = 300
autoscaling_group_name = aws_autoscaling_group.prodxcloud-autoscaling-group.name
}

resource "aws_cloudwatch_metric_alarm" "cpu_high" {
alarm_name = "cpu_high"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "120"
statistic = "Average"
threshold = "70"

dimensions = {
AutoScalingGroupName = aws_autoscaling_group.prodxcloud-autoscaling-group.name
}

alarm_actions = [
aws_autoscaling_policy.scale_up.arn
]

ok_actions = [
aws_autoscaling_policy.scale_down.arn
]
}

resource "aws_cloudwatch_metric_alarm" "cpu_low" {
alarm_name = "cpu_low"
comparison_operator = "LessThanThreshold"
evaluation_periods = "2"
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "120"
statistic = "Average"
threshold = "30"

dimensions = {
AutoScalingGroupName = aws_autoscaling_group.prodxcloud-autoscaling-group.name
}

alarm_actions = [
aws_autoscaling_policy.scale_down.arn
]

ok_actions = [
aws_autoscaling_policy.scale_up.arn
]
}
  • resource “aws_autoscaling_group” “example”: Defines an Auto Scaling group named example.
  • launch_configuration: References the launch configuration.
  • min_size, max_size, desired_capacity: Set the minimum, maximum, and desired number of instances.
  • vpc_zone_identifier: List of subnet IDs where the instances will be launched.
  • tag: Tags the instances for identification.

You can now check your created auto-scaling group in your AWS console

A step-by-step guide for AWS EC2 provisioning using Terraform: EC2 Auto scaling using iac

Update: Once you are done with this tutorial, you might want to check a follow-up tutorial on the next part, The Guide to Terraform DevOps: AWS EC2 Instance using IaC

Conclusion

What is the purpose of EC2 Auto Scaling? Amazon EC2 Auto Scaling is a service that helps ensure you have the optimal number of Amazon EC2 instances to handle the load of your application. It automatically adjusts the number of instances in response to the demand, scaling out to accommodate high-traffic periods and scaling in during low-traffic periods to minimize costs. You achieve this by creating collections of EC2 instances called Auto Scaling groups. These groups have specified minimum, maximum, and desired instance counts, and are governed by scaling policies and health checks to maintain application performance and availability. This ensures seamless handling of traffic spikes and efficient use of resources.

Thank you for Reading !! 🙌🏻, don’t forget to subscribe and give it a CLAP 👏, and if you found this article useful contact me or feel free to sponsor me to produce more public content. see me in the next article.🤘

For more information about the author ( Joel O. Wembo ) visit:

Links:

--

--

Joel Wembo

I am a Cloud Solutions Architect at prodxcloud. Expert in AWS, AWS CDK, EKS, Serverless Computing and Terraform. https://www.linkedin.com/in/joelotepawembo