Lambda Function to Start and Stop RDS Instance

In this article, We are going to perform We have covered Creating IAM Policy in AWS, Creating IAM Role and Attach Permission Policies, Lambda Function to Start and Stop RDS Instance and Creating CloudWatch Events to start and Stop RDS instance.

Introduction

If we want to reduce AWS cost then we can stop AWS resources in off hours and weekends. here we are going to cover how to start and stop Postgres RDS instance using lambda function and scheduling cron job in cloudwatch for same.

Prerequisites/AWS Services Used

  • Postgres or other RDS Instance
  • IAM Policy and Role
  • Lambda Functions
  • CloudWatch Events

Below are steps to start and stop RDS instance using Lambda function

Step #1: Creating IAM Policy in AWS

We have to create IAM Policy and Role which contains execution permission to RDS instance and cloudwatch which we have to attach to Lambda function.

To create IAM policy and Role Login to AWS Management console and search “iam” in search box.

login-aws-manament-console-and-search-iam_1

You will redirected to IAM dashboard, click on Policies at left side.

redict-iam-dashboard_2

Click on Create Policy

click on create policy 3

Select JSON and paste the below policy into it and click on Tags.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "rds:StopDBInstance",
                "rds:StartDBInstance"
            ],
            "Resource": "*"
        }
    ]
}
select option json editor paste the policy and click on Tags 4

Add tags if you want and Click on Review

add tag and click on review 5

Give Name and Description to IAM Policy and click on Create Policy.

give name the policy click on create policy 5

Step #2: Creating IAM Role and Attach Permission Policies

Next We have to create role and attaching policy which we have created above to it.

To create role navigate to IAM and click on Roles on left side and click on Create Role.

click on create role 5

Select AWS service ,select Lambda and click on Permissions.

select lambda under aws services 6 1

Attach existing policy which created above and click on Tags.

attach existing policy and click on tags 7

Give the tag.

add tags to role 8

Enter Role name and Role Description and click on Create Role.

give role name click on create role 9

Step #3: Lambda Function to Start and Stop RDS Instance

Below are steps Lambda function to start and stop RDS Instance.

Step #3.1: Lambda Function to Stop RDS Instance

Next Search Lambda and click on Create function.

search lambda and click on create function 10

In Author from scratch section give function name, Select Runtime as Python 3.7.

author from sratch function name and runtime 11

Under Permissions section, select use an existing role, in existing role add role which we have create above and click on Create function .

permissions use an existing role and click on create function 12

Copy the below Python Lambda function code to stop RDS Instance , change RDS instance name and region according to your and click on deploy.

import boto3
region = 'ap-south-1'
rdsInstances = ['demo']
def lambda_handler(event, context):
    rds = boto3.client('rds', region_name=region)
    for i in rdsInstances: 
        print('Stoping RDS '+ i) 
        rds.stop_db_instance(DBInstanceIdentifier=i)
    print (' stopped your RDS instances: ' + str(rdsInstances))
Lambda function code 1

Testing Lambda function to Stop RDS Instance.

Click on Lambda function, Go to Test, click on Configure test Events.

click on configure test events 2

Give Event name and click on Create.

give the event name and click on create 3

Then click on Test. Now if everything is configures properly, Now RDS instance will stop.

Step #4: Creating CloudWatch Events to start and Stop RDS instance

Click on cloudwatch, you will be navigated to CloudWatch Console, Under Events , click Rules, Click on Create Rule.

Here you option Event Pattern and Schedule, Click on Schedule you can use Fixed rate or cron Expression.

If we want to schedule using Cron Expression, schedule job using UTC Time and Add Target , Select Lambda function and Click on

Configure Details. Now RDS instance stop as per cron expression time.

cloudwatch rule and add target 4

Step #3.2: Lambda Function to Start RDS Instance

Use Same IAM Policies and Role.

Create a New Lambda function to start RDS Instance and configure new test events, Below is Lambda function code to start RDS Instance, change RDS instance name and region according to your.

import boto3
region = 'ap-south-1'
rdsInstances = ['demo']
def lambda_handler(event, context):
    rds = boto3.client('rds', region_name=region)
    for i in rdsInstances: 
        print('Starting RDS '+ i) 
        rds.start_db_instance(DBInstanceIdentifier=i)
    print (' started your RDS instances: ' + str(rdsInstances))

Next create same CloudWatch Events and Rule as shown above to start RDS instance as per CloudWatch Rule.

Conclusion:

We have covered Creating IAM Policy in AWS, Creating IAM Role and Attach Permission Policies, Lambda Function to Start and Stop RDS Instance and Creating CloudWatch Events to start and Stop RDS instance.

Related Articles:

How to Create Ubuntu Instance in AWS [7 Steps]

How to connect to AWS EC2 Instance using MobaXTerm

How to Enable Password Authentication for AWS EC2

How to Connect EC2 Instance using Putty

How to Transfer files to AWS Instance using WinSCP [2 Steps]

How to Create AWS DocumentDB and Connect [3 steps]

How to Install MySQL 5.7 on Amazon Linux 2

AWS Create Instance from snapshot

AWS Create EC2 Instance from Snapshot

How to Create IAM User in AWS Step by Step

How to create Linux EC2 Instance in AWS

Reference:

AWS Official page

About DevOps Hint

DevOps Hint Founded in 2020 Community Site where you can find about How to Guides, Articles and Troubleshooting Tips for DevOps, SRE, Sysadmins and Developers.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link