Start / Stop EC2 instance using AWS Lambda Function.

techwithpatil
3 min readSep 4, 2024

--

In this blog, I will show you how to stop and start the instance using the AWS Lambda function

AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. You can trigger Lambda from over 200 AWS services and software as a service (SaaS) applications, and only pay for what you use.

To know more about Lambda refer to AWS documentation. The link below; https://aws.amazon.com/lambda/

To start this Demo we need to create an EC2 instance first. If you don’t know how to create an EC2 instance then check out my previous blog

Let’s start 😎

📌 Task 1️⃣

  • Hope you have created an EC2 instance.
  • Create Lambda Function. To create follow the below steps;
  • Name the function → Run time- dropdown and select python because in this demo we are using python script → create function
  • Copy the below Python script and paste it into the code source (make sure to add the instance ID of your instance and give the region)
  • The below script will stop the instance we created.
import boto3
region = 'us-east-1'
instances = ['INSTANCE ID']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.stop_instances(InstanceIds=instances)
print('stopped your instances: ' + str(instances))
  • Go to configuration → permission →Click on the IAM role link it will open IAM console
  • Attach the policies below
  • By default, Lambda will create only one role.
  • Search for ec2 and cloud watch then add both full access permission
  • Now we should have all these 3 permissions
  • Go back to the Lambda function and click on ‘Test’
  • Click on the Test button again
  • Go to the instance and check now we can see the instance has been stopped
  • Now we have used the lambda function to stop the instance

📌 Task 2️⃣

Let’s see how to start the instance using the lambda function.

Go to the Lambda function we created and replace the code

import boto3
region = 'us-east-1'
instances = ['Instance-ID]
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
ec2.start_instances(InstanceIds=instances)
print('started your instances: ' + str(instances))
  • Go back to the instance and check now we can see the instance is up and running

📌Task 3️⃣

🧹 Clean UP

  • Terminate the instance
  • Delete Lambda Function

Thank you!🤗

--

--

techwithpatil
techwithpatil

Written by techwithpatil

DevOps & Site Realiability Interview | Cloud | AI Agent | Software Automation https://beacons.ai/techwithpatil

Responses (1)