DEV Community

Manoj Swami
Manoj Swami

Posted on

Automate EC2 Instance Management with AWS Lambda

Title: Automating EC2 Instance Management with AWS Lambda and API Gateway

Introduction

Managing EC2 instances can sometimes be a hassle, especially when you need to start or stop them manually. In this guide, we'll show you how to automate this process using AWS Lambda, triggered by both API Gateway and CloudWatch Events. This approach allows you to manage your instances efficiently, ensuring they are running only when needed.

Prerequisites

Before starting, make sure you have:

  • An AWS account
  • Basic knowledge of AWS Lambda, EC2, and API Gateway
  • An EC2 instance running in your AWS account

Step-by-Step Guide

1. Create a Lambda Function

Go to the AWS Lambda console and create a new function:

  • Name: ManageEC2Instance
  • Runtime: Python 3.x

Add the following code to your Lambda function:

import boto3
import json

def lambda_handler(event, context):
    ec2 = boto3.client('ec2')
    instance_id = 'i-015680d45acd5f92f9'  # Replace with your instance ID

    try:
        response = ec2.describe_instances(InstanceIds=[instance_id])
        state = response['Reservations'][0]['Instances'][0]['State']['Name']

        if state == 'running':
            ec2.stop_instances(InstanceIds=[instance_id])
            message = 'Instance was running, now it is stopping.'
        elif state == 'stopped':
            ec2.start_instances(InstanceIds=[instance_id])
            message = 'Instance was stopped, now it is starting.'
        else:
            message = f'Instance is in "{state}" state; no action performed.'

        return {
            'statusCode': 200,
            'body': json.dumps(message)
        }
    except Exception as e:
        return {
            'statusCode': 400,
            'body': json.dumps(str(e))
        }
Enter fullscreen mode Exit fullscreen mode

Lambda Function

2. Set Up Permissions

Attach a policy to your Lambda function that allows it to manage EC2 instances. You can use the AmazonEC2FullAccess policy for simplicity, but for production, consider creating a custom policy with just the necessary permissions.

3. Create an API Gateway

Set up an API Gateway to trigger the Lambda function:

  • Create a new HTTP API.
  • Add a GET method (e.g., /manage-instance).
  • Integrate this method with your Lambda function.
  • Deploy the API to obtain the endpoint URL.

4. Testing the API

You can test the API using a browser or any HTTP client:

  • URL Format: https://<API_ID>.execute-api.<REGION>.amazonaws.com/manage-instance
  • When accessed, the function will:
    • Start the instance if it’s stopped.
    • Stop the instance if it’s running.
    • Provide a message indicating the action taken.

5. Automate with CloudWatch Events

To automate the start/stop process based on a schedule:

  • Go to CloudWatch Events.
  • Create a rule for scheduled actions (e.g., start at 8 AM, stop at 6 PM).
  • Set the target to your Lambda function.

CloudWatch Schedule Event

Conclusion

With this setup, you can manually control your EC2 instances via a simple URL and automate start/stop actions using CloudWatch Events. This solution helps optimize costs by ensuring your instances run only when needed.

Summary

Automating EC2 instance management with AWS Lambda and API Gateway simplifies your workflow and reduces costs. This setup allows you to control instances manually and schedule them to meet your specific needs.

Top comments (1)

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!