Start and Stop Your AWS EC2 Instances Automatically

Parag Poddar
Tensult Blogs
Published in
2 min readAug 27, 2019

This Blog has moved from Medium to blogs.tensult.com. All the latest content will be available there. Subscribe to our newsletter to stay updated.

https://bit.ly/2Zi3hCs

The use of this automation is to stop and start EC2 instances at a certain time every day. In our use case, we stop instances every night and start those instances in the next morning.

Note: To implement this automation on EC2 instances, you have to add a tag in your instances. Tag key is autostartandstop and the tag value is true.

Let's start deploying the automation in AWS...

Create an IAM role for Lambda

Use the following inline policy to create the role:

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"ec2:DescribeInstances",
"ec2:StartInstances",
"ec2:StopInstances",
"logs:CreateLogGroup",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}

Create a Lambda function

Create a Lambda with the runtime of Node.js 8.10 or above and select the IAM role previously created. Copy the Lambda code from here and after that paste in your Lambda function and save it.

Create CloudWatch Event rules

To know how to create a CloudWatch Event rule, set a cron expression and add Lambda trigger, please see AWS CloudWatch Event documentation.

Rule 1 to start EC2 instances

Set a Cron expression when you want to stop instances and add Lambda trigger in it (Select Lambda function which is created before). Copy and paste the following JSON test under Configure input>Constant (JSON text): {“action”: “start”}

Rule 2 to stop EC2 instances

Set a Cron expression when you want to start instances and add Lambda trigger in it (Select the same Lambda function here also). Copy and paste the following JSON test under Configure input>Constant (JSON text): {“action”: “stop”}

Conclusion

So, we have successfully deployed EC2 start and stop automation in AWS.

I look forward to seeing what you’re going to use it for, please share your results with me in the comments section.

--

--