I needed to figure out a way to start/stop instances automatically during certain periods. The obvious way is Lambda, but how to do it. We wanted some instances to run from Monday to Friday, and to start at 7am and stop at 5pm.

Luckily there is a library that abstracts everything you need for starting and stopping your instances. And coupled with Lambda and CloudWatch we can easily accomplish what we want.

IAM Role

First thing let’s create a new IAM role. The role is defined bellow, so we need some things so we can create logs and allow our Lambda functions to be able to start/stop an instance, with the following steps.

Go to IAM Management console

Roles

Create New Role

Role Name: lambda_start_stop_ec2

Role Type

AWS Service Roles: AWS Lambda

Create role

Edit lambda_start_stop_ec2 role, and create a new custom inline policy with the json contents bellow.