Create a AWS Lambda Function to Stop and Start RDS Instance

I am getting request from friends to stop the Relational Database Service (RDS) instance after peak workload times. I am going to use AWS Lambda functions to stop the RDS instance. You can use the same steps to stop other supported types of instances, like MySQL, PostgreSQL, SQL Server or MariaDB.

Below mention steps to stop the RDS instance using Lambda functions.

Step 1: Login in the AWS console.

Step 1.1: Create an IAM role to enable access to start and stop an RDS instance and to enable CloudWatch logs.

Login into the IAM console and click on Policy and Create Policy.

Step 1.2: Once Create Policy editor open than select JSON and replace with the below JSON in the editor

{
    "Version": "2012-10-17",
    "Statement": [
        {           
            "Effect": "Allow",
            "Action": [
                "rds:DescribeDBInstances",
                "rds:StopDBInstance",
                "rds:StartDBInstance"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

Step 1.3: Give a policy name: start_stop_RDS_policy, along with a description and click on “Create Policy”

Step 1.4: Now in the IAM console click on Roles and Create Roles

Step 1.5: Choose AWS Services, Lambda as your service and Click on Next Permission.

Step 1.6: In the Search bar search for “start_stop_RDS_policy” and the policy you created earlier should appear as below.

Step 1.7: Provide a role name, start-stop-rds-lambda, and click Create Role.

Step 2: Create a Lambda function.

Step 2.1: To create a lambda function open the Lambda Service console and Click on Create Functions than Select Author from Scratch.

Provide the Basic Information:

Function Name – Stop_RDS_Inst

Runtime – Python 2.7

Under permission click on “Choose and create an existing Role” and Select “Existing Role” and choose the role created “start-stop-rds-lambda”.

Step 2.3: Click on Create Function

Step 2.6: Lambda function will be created as shown below.

Now make a note of ‘ARN‘ which is available at the top right corner which is used to grant permissions for the Lambda function to access Lambda API “GetFunctionConfiguration” and access to the environment variables.

Step 2.4: Go to the rule “start_stop_RDS_policy” and click on Add inline policy.

Step 2.5: Go to the JSON tab and enter as mention below then change the Resource to the Lambda ARN refer the step no 2.6 top right “ARN” value Example: “us-east-1:632886776519:function:RDSInstanceStop”.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:GetFunctionConfiguration",
            "Resource": "arn:aws:lambda:::function:RDSInstanceStop"
        }
    ]
}

Step 2.6: Give the name to the policy rds_stop_policy and click on Create Policy

Step 3: In the Python function, update the Code

import sys
import botocore
import boto3
from botocore.exceptions import ClientError


def lambda_handler(event, context):

    rds = boto3.client('rds')
    lambdaFunc = boto3.client('lambda')

    print 'Trying to get Environment variable'
    try:
        funcResponse = lambdaFunc.get_function_configuration(
            FunctionName='RDSInstanceStop'
        )

        DBinstance = funcResponse['Environment']['Variables']['DBInstanceName']

        print 'Stoping RDS service for DBInstance : ' + DBinstance

    except ClientError as e:
        print(e)    

    try:
        response = rds.stop_db_instance(
            DBInstanceIdentifier=DBinstance
        )

        print 'Success :: ' 
        return response
    except ClientError as e:
        print(e)    
    return
    {
        'message' : "Script execution completed. See Cloudwatch logs for complete output"
    }

Step 3.1: Now configure the environmental variable as mention below:

Key – DBInstanceName -> Never change the key value

Value – testdbind01 -> Give your RDS instance Name

Step 3.2: Now test the Lambda function created. On the top right corner next to Action tab select the Test and Configure the Test events

Step 3.3: Select Create New Test Event and select the Hello World event template.

Step 3.4: When you click on the execution should succeed.

Step 4: Configure the Schedule to monitor and stop the instance automatically based on lean time.

Step 4.1: Go to cloud watch and click on rules than click on Create Rules.

Step 4.2: In Event Source, select the Schedule and then select the cron expression. Now go to Targets, select the Lambda functions and In functions select the stop-rds-function and click on Configure Details

Now your instance will automatically shutdown based on your configured scheduled. It is not recommended to keep the instance down it will impact the instance maintenance task which will be done in the backed by AWS.

Note: Before implementation please check your environment and apply the above steps accordingly.

WP2Social Auto Publish Powered By : XYZScripts.com