+91 – 7838219999

contact@nitinfotech.com

HomeTech SolutionsAWS CloudAutomatically Stop RDS Instances (2 or more) with Lambda function

Automatically Stop RDS Instances (2 or more) with Lambda function

Saturday, December 21, 2024

To stop RDS instances automatically if they start, you can enhance the Lambda function to handle multiple instances. Here’s how to set it up:

Stop RDS Instances – Step-by-Step Guide

  1. Open the Amazon SNS console.
  2. Create a new topic and subscribe your email or phone number to receive notifications.

2. Create a Lambda Function

1. Open the AWS Lambda console and create a new function:

  • Choose Create function.
  • Select Author from scratch.
  • Provide a function name, e.g., Stop RDS Instances.
  • Choose a runtime, e.g., Python 3.x.

2. Add Permissions:

  • Ensure the Lambda execution role has the necessary permissions to describe and stop RDS instances and publish to SNS. Attach the following policies to the role:

a) AmazonRDSFullAccess

b) AmazonSNSFullAccess

3. Add the Lambda Function Code:

  • In the function code section, add the following code to handle multiple RDS instances:
import boto3
import json
 
def lambda_handler(event, context):
    rds_client = boto3.client('rds')
    sns_client = boto3.client('sns')
    # List of RDS instance identifiers to monitor
    rds_instances = ['rds_instance_id1', 'rds_instance_id2']
    # SNS topic ARN for notifications
    sns_topic_arn = 'your-sns-topic-arn'
    messages = []
    for instance_id in rds_instances:
        response = rds_client.describe_db_instances(DBInstanceIdentifier=instance_id)
        status = response['DBInstances'][0]['DBInstanceStatus']
        if status == 'available':
            rds_client.stop_db_instance(DBInstanceIdentifier=instance_id)
            message = f"RDS instance {instance_id} was automatically stopped."
            messages.append(message)
            sns_client.publish(TopicArn=sns_topic_arn, Message=message, Subject='RDS Instance Stopped')
    return {
        'statusCode': 200,
        'body': json.dumps(messages)
    }

4. Deploy the Lambda Function:

  • Deploy the code by saving the function.

3. Create a CloudWatch Event Rule

1. Open the CloudWatch console and create a new rule:

  • Navigate to Rules and click Create rule.
  • Select Event Source as Event Pattern.
  • Use the following event pattern to filter for RDS instance state changes:
{ 
   "source": ["aws.rds"], 
    "detail-type": ["RDS DB Instance Event"], 
     "detail": {
          "EventCategories": ["availability"] 
       }
 }

2. Add Target:

  • In the Targets section, select Add target and choose Lambda function.
  • Select the Lambda function you created.
  • Configure the target and click Create Rule.

Testing and Verification

Test the Lambda Function:

1. Manually invoke the Lambda function to ensure it correctly identifies the RDS instance statuses and stops them if necessary.
2. Check the logs in CloudWatch to ensure the function executes correctly.

Monitor the Setup:

1. Ensure you receive notifications via SNS if the RDS instances are stopped.
2. Verify that the Lambda function runs as expected whenever an RDS instance changes status to available.

Summary

By following these steps, you can automate the process of stopping two RDS instances (rds_instance_id1 and rds_instance_id2) if they start manually or automatically. This setup ensures that the instances do not remain running unintentionally, helping to control costs and maintain security.