Logo

dev-resources.site

for different kinds of informations.

Automate EC2 Instance Management with AWS Lambda

Published at
6/29/2024
Categories
lambda
ec2
cloudwatch
Author
manojspace
Categories
3 categories in total
lambda
open
ec2
open
cloudwatch
open
Author
10 person written this
manojspace
open
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.

cloudwatch Article's
30 articles in total
Favicon
Monitoring AWS Infrastructure: Building a Real-Time Observability Dashboard with Amazon CloudWatch and Prometheus
Favicon
A Simple Guide to AWS Monitoring Tools
Favicon
Config AWS Cloudwatch Application Signals Transaction Search with CDK
Favicon
Quickly and easily filter your Amazon CloudWatch logs using Logs Insights
Favicon
Forward logs to Cloudwatch for an EC2 instance running a custom Linux AMI
Favicon
AWS CloudWatch: Implementing Data Protection Policy for Sensitive Log Data!
Favicon
Config AWS Cloudwatch Application Signals for NodeJs Lambda with CDK
Favicon
AWS CloudWatch Logging and Live Tail using AWS CLI!
Favicon
AWS CloudWatch Logging and Live Tail using Python/Boto3 SDK!
Favicon
A Beginner’s Guide to Amazon CloudWatch: Monitoring Your Cloud Like a Pro
Favicon
Automatização de Reboots de Instâncias EC2 com CloudWatch, EventBridge e Lambda
Favicon
Streaming of Desktop Applications Securely on Web Browser Using Amazon AppStream 2.0
Favicon
How to Use Send AWS CloudWatch Metrics to GreptimeCloud by Grafana Alloy
Favicon
AWS CloudWatch Logging and Live Tail!
Favicon
Understanding Logging in Kubernetes - From Containers to Nodes
Favicon
AWS CloudWatch Observability Solutions: Game-Changer or Just a Glossy Wrapper? Honest First Impressions!
Favicon
AWS Lambda Log Aggregation Using CloudWatch Custom Log Group & Logs Insights!
Favicon
AWS Logging, Monitoring & Auditing with AWS CloudWatch and CloudTrail!
Favicon
Amazon CloudWatch Internet Monitor from Amazon Network Load balancer
Favicon
AWS Monitoring - Part 1: AWS CloudWatch
Favicon
AWS Database Migration Service now includes enhanced monitoring dashboard for your DMS tasks
Favicon
CloudWatch CPU Utilization Monitoring with SNS Alert
Favicon
VPC Flow Logs Setup
Favicon
Transfer of Data Across Accounts from S3 to S3 Using AWS DataSync
Favicon
Real-Time Incident Recovery with Event-Driven Microservices Architecture and Early Monitoring
Favicon
Implementing SLO Error Budget Monitoring with AWS Services Only
Favicon
Gerenciamento de alta latência com AWS CloudWatch e AWS Systems Manager
Favicon
Creating Recommended Alarms for Amazon OpenSearch Service with Terraform
Favicon
Automate EC2 Instance Management with AWS Lambda
Favicon
Deep Dive on AWS Clean Rooms with Integration to AWS Glue

Featured ones: