How to Start/Stop the EC2 Instance by using Lambda Function

To Start/Stop the EC2 Instance by using Lambda Function

Introduction:

AWS Lambda is a serverless compute service that can run the code in response to events and manages the compute resources that can use AWS Lambda to extend other AWS services with custom logic or create the own back-end services that run at AWS scale, performance, and security. Amazon Elastic Compute Cloud (Amazon EC2) is a web service that delivers reliable, resizable compute capacity in the cloud that is designed to make web-scale cloud computing more comfortable for developers.

Login to your AWS account:

In console page select EC2 to create a new instance: Create a new a Instance:

Then create a role for Lambda function with permission: Then open the new role and create a inline policy: Add ARN to restrict the Instances: Create a Lambda Function: This is the Function I had written to stop the instance: Then Increase the execution time in settings: Deploy the changes and run the function:

It will show the status of the instance is stopped: Then start the Instance by changing the code in function: With this method to Start/Stop the EC2 instance by using Lambda Function comes to an end.

FAQ
Q
How long can an AWS Lambda function execute?
A
AWS Lambda functions can be configured to run up to 15 minutes per execution. You can set the timeout to any value between 1 second and 15 minutes.
Q
How does AWS Lambda isolate my code?
A
Each AWS Lambda function runs in its own isolated environment, with its own resources and file system view. AWS Lambda uses the same techniques as Amazon EC2 to provide security and separation at the infrastructure and execution levels.
Q
How does a lambda function work?
A
AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time that you consume—there is no charge when your code is not running.
Q
What languages does AWS Lambda support?
A
AWS Lambda natively supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby code, and provides a Runtime API that allows you to use any additional programming languages to author your functions. Please read our documentation on using Node.js, Python, Java, Ruby, C#, Go, and PowerShell.
Q
What is AWS Lambda?
A
AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you. You can use AWS Lambda to extend other AWS services with custom logic or create your own back-end services that operate at AWS scale, performance, and security.