Posted on 10 June 2020, updated on 21 April 2023.
You can optimize the cost of cloud infrastructure by shutting down the instances of developers at night and on weekends and launching them back on the working mornings. We’ll see how to scale down our EC2 instances at night and on weekends and scale up back the autoscaling group at day.
Let’s see how easy it is to set up that on the following structure:
On this situation, we want to “shut down” the ASG (autoscaling group) containing the Kubernetes Node, which means our application used by the developers. We want to scale the desired number of instances to 0 at night, and setting it back to the desired number during the day.
We’ll use in this situation the following component (and you might want to terraform them):
- AWS IAM Role (and its policy)
- AWS Lambda function
- AWS CloudWatch Rule
AWS IAM Role
First, we’ll need the IAM role necessary for the AWS Lambda. Go to the IAM section and create a policy:
Then, we’ll create the role who’ll use this policy:
We’ll pass the tag section
AWS LAMBDA
Now we need to create the lambda that will start and shutdown your instance inside your autoscaling group, you need to get the id of your autoscaling group, you can find it there:
Write down the Name of your autoscaling group.
Now create the Lambda that will start and stop your instances:
Make sure to pick Python 2.7 and your existing role created.
Then we’ll add the following code to the function code of this lambda:
AWS Cloudwatch Rules
Then we’ll create both start and stop CloudWatch rules:
For the cron expression, we are making here the instances start at 06:15:00 GMT, but you can choose another expression.
With the following parameters (make sure to replace asg_name by your autoscaling name and change aws_region if you are not in eu-west-3)
Then we need to create the stop instances CloudWatch rule:
For the cron expression, we are making the instances stop at 20:00:00 GMT, but you can choose another expression.
With the following parameters (make sure to replace asg_name by your autoscaling name and change aws_region if you are not in eu-west-3)
By setting the MinSize and DesiredSize to 0, you stop all the instances inside your auto-scaling group, set those parameters back to your configuration (here 3), and start back the instances. We now have seen how easily we can stop our EC2 instances at night to save money on our cloud bill. You should monitor your ec2 instance with Cloudwatch, to make sure your autoscaling is done properly.