AWS Lambda to start and stop EC2 instances

There are a variety of situations where having a microservice available that can start or stop EC2 instances at will can be handy. In this article we are going to see how we can use an AWS Lambda to do such a thing on demand without using any extra servers or instances at all.

Create the AWS Lambda Code to start and stop EC2 instances

The code is pretty simple and it's available at GitHub in this repo https://github.com/marcelog/aws-lambda-start-stop-instances.

To use it, clone the repo and prepare the code like this:

Now go to your AWS Lambda console and create a NodeJS 4.3 lambda function and then select the "Code" tab and upload the .ZIP file just created.

AWS Role and Policy Needed to Start and Stop Instances from Lambda

What follows is the needed policy that your Lambda needs in its role so it can start and stop EC2 instances. Note that we are also including the ec2:DescribeInstances and ec2:DescribeInstanceStatus, because in our code we output a debug message that clearly shows some information about the target instance, but this is not needed per se in order to start it or stop it.

Testing and Using your Lambda

The code expects to receive events like this:

And you can use stop as the action if you want to stop a specific instance. To test the code, go to your new lambda function and click "Test", then paste the example event.