Start, Stop or Restart EC2 Instance using Lambda Function
Start, Stop or Restart EC2 Instance using Lambda Function

In this article, Let’s check out What is AWS Lambda Function & How we can use Lambda function to restart the EC2 server server instance.

Video Tutorial

What is AWS Lambda Function?

The AWS Lambda Function is a service provided by Amazon Web Services(AWS) that is basically a server less computing service. Using Lambda function we can run code without managing any servers instance. Here instead of building a overall server infrastructure, you can keep you focus on developing a application’s function code that can we executed when an events occurs or triggers is hit.

Basically AWS Lambda function is a server less computing system, Languages supported are Node.JS, Python, Java, Go, Ruby,C#, PowerShell and custom runtimes.

How to create a Lambda Function in AWS console?

1. SignIn into AWS Console.

2. In search box above search “Lambda”

how to create a lambda function in aws

select it.

3. Click on “Create Function” and fill the form

how to create a lambda function in aws

Here select "Autor from scratch", give a name to function, In Runtime select the language maybe python, nodejs or any other which you prefer to write code on. I select Python 3.11.

The AWS Lambda function get’s created, here is where you need to write your code.

how to create a lambda function in aws

How to change lambda execution time

Usually when you execute a lambda function by default the function execution timeout is 3 sec, suppose your lambda function need more time to execute the whole code then your code will stop execution after 3 sec and you may see an warning “Task timed out after 3.00 seconds”, so you need to change or config lambda function execution timeout below are steps to change timeout.

in lambda function, Goto Configuration -> general configuration, click on Edit

how to change lambda function execution time

Now change AWS lambda function timeout as per your need

AWS lambda function timeout

Note: This is required because sometime the code might require more then 3 sec to fully execute, In our case we are going to write a lambda function that stop our EC2 instance and start it again so for this process our server need at least 3-5 minute to start fully.


Giving permission to lambda function to access EC2 instance

As we are implementing a lambda function that can communicate to EC2 instance and perform event like stop, start or restart the instance server from lambda function itself we need to give permission to access EC2 instance. below are the step:

1. In AWS Console, Top Search Box, search for IAM, Enter the service.

2. Now on side menu goto Roles > select lambda function roles as shown in below image

Next in Permission tab > Permissions policies > click on Add Permission > Attach Policy

Now in Other permissions policies search box, search for “EC2FullAccess”

aws roles add permission for lambda function

Check the Check box and click on Add Permission

AmazonEC2FullAccess add permission to Lambda function

Once you add the roles permission to full access EC2 instance, your lambda function will be able to fully control your EC2 instance.


Lambda Python Code to Stop, Start EC2 Instance

Code – python

import boto3
import time
def lambda_handler(event, context):
    
    ec2 = boto3.client('ec2')
    
    # Specify the instance IDs of the instances you want to start
    instance_ids = ['i-091182e12341c19fd'] // replace with your ec2 instanceID

    
    # Stop the instances
    response = ec2.stop_instances(InstanceIds=instance_ids)
    
    time.sleep(300)

    # Start the instances
    response = ec2.start_instances(InstanceIds=instance_ids)
    print("Started")
    
    return response

To run the code, click on Deploy Button then click on Test Button

how to run lambda function