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…


This content originally appeared on DEV Community and was authored by Manoj Swami

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))
        }

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.


This content originally appeared on DEV Community and was authored by Manoj Swami


Print Share Comment Cite Upload Translate Updates
APA

Manoj Swami | Sciencx (2024-06-29T05:39:20+00:00) Automate EC2 Instance Management with AWS Lambda. Retrieved from https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/

MLA
" » Automate EC2 Instance Management with AWS Lambda." Manoj Swami | Sciencx - Saturday June 29, 2024, https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/
HARVARD
Manoj Swami | Sciencx Saturday June 29, 2024 » Automate EC2 Instance Management with AWS Lambda., viewed ,<https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/>
VANCOUVER
Manoj Swami | Sciencx - » Automate EC2 Instance Management with AWS Lambda. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/
CHICAGO
" » Automate EC2 Instance Management with AWS Lambda." Manoj Swami | Sciencx - Accessed . https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/
IEEE
" » Automate EC2 Instance Management with AWS Lambda." Manoj Swami | Sciencx [Online]. Available: https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/. [Accessed: ]
rf:citation
» Automate EC2 Instance Management with AWS Lambda | Manoj Swami | Sciencx | https://www.scien.cx/2024/06/29/automate-ec2-instance-management-with-aws-lambda/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.