Automate EC2 Instance Management with AWS Lambda
Tags: lambda, ec2, cloudwatch
Published: 2024-06-29 05:39:20

## 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:

```python
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/220t29fkvdj3slkvihuk.png)



#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3cjoy4ypa3s3vdsji2nm.png)


### 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.