EC2 Instance auto stop with CloudWatch and Lambda
Overview
To stop the EC2 instance automatically by given time if user forgot to stop manually.
Architecture
Amazon CloudWatch Setting
CloudWatch Rule
Rules name : Stop_EC2_Instances
Cron Expression : 30 16 ? * MON-FRI *
It will execute every Monday to Friday at 4:30 PM GMT (11 PM Myanmar Time)
CloudWatch connect with AWS Lambda
In this time, I will connect to AWS Lambda named EC2_Instances_Stop. Its include the source code to stop the EC2 instances.
Procedure Overview
Set the scheduler in Amazon CloudWatch to execute AWS Lambda.
When executing AWS Lambda, it will retrieve the EC2 instance information (Region and Instance ID) from Amazon S3 to operate the EC2 instances.
In Amazon S3, keep the json file with the following data format existed inside the ec2-instances.json:
“region” : target EC2 instances region
“instances” : target EC2 instances array which user don’t want to stop automatically.
{
"region": "us-east-1",
"instances" : []
}
Existing instances list
[
i-07034bbf7e161fa10,
i-0e414c01778369472
]
In ec2-instanes.json
{
"region": "us-east-1",
"instances" : [i-07034bbf7e161fa10]
}
AWS Lambda code
BUCKET_NAME : <name of the s3 bucket>
OBJECT_NAME : <object name which exist in s3 bucket>
Comments