EC2 Auto-Scaling and Launch Templates
I had not created an EC2 instance in forever, but recently I got a chance when I was trying to do something new and also got to learn about the new Launch Templates. In this post I will create a launch template and then use it to create an auto-scale group and see it in action by CPU utilization. The console experience sure has changed but it is easy to try out and see the differences.
Step 1 — Create a Launch Template
In the EC2 console create a new Launch Template (previously was launch configurations). I picked the AWS Linux AMI, t2 micro instance and the specific options to note:
- Enable “Detailed CloudWatch monitoring” — this captures metrics more frequently so we have better charts to show.
- Set user data as follows to peg the CPU using the
stress
utility.
#!bin/bash
yum update -y
yum install stress -y
/usr/bin/stress --cpu 2 --timeout 10m
This will cause the EC2 instance to run stress
for 10 minutes as soon as the instance is ready.
Step 2 — Create Auto-Scaling Group
Next, in the EC2 console create a new auto-scaling Group using the previously created launch template. I picked the default VPC and default subnets in multiple AZs. For this demo purposes it does not matter, and no access is required to the EC2 instances, but if you would like to SSH in and check using top
then make sure the security group you pick has the right rules and you have external access to your VPC.
- Set desired=1, min=1 and max=3
- Use the Target Tracking policy with CPU metric. This will trigger the scale out and scale in.
Complete the create and it will set the EC2 instance creation in motion! Here are some relevant metrics. Even if your instances are terminated you can retrieve this data from CloudWatch.
Step 3 — Shutdown
Since I set min=1 there will always be 1 EC2 instance running and if you terminate just the instance then guess what — the auto-scaling will kick in and bring it back up! So, at the end of this please delete the auto-scaling group and that will take care of terminating the remaining instance.
If these topics interest you then reach out to me and I will appreciate any feedback. If you would like to work on such problems you will generally find open roles as well! Please refer to LinkedIn.