DEV Community

cloudy
cloudy

Posted on

Run RDS start of month

If you have a requirement to keep the AWS RDS running only few days at the start or end of the month and unable to use Instance Scheduler, setup a lambda function to trigger based on cronjob using the following python script.

Following lambda python script will stop the RDS based on the environment variable configured on the lambda function. You can setup another function to start separately by modifying rds.stop_db_instance to rds.start_db_instance

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


def lambda_handler(event, context):
    # TODO implement

    rds = boto3.client('rds', region_name='ap-southeast-2')
    DBinstance = os.environ.get('DBInstanceName')

    try:
        dt = datetime.datetime.today()
        print(dt)
        if dt.day == 1 or dt.day == 2:
            print("Skip...")
        else:
            print("Continue...")
            response = rds.stop_db_instance(DBInstanceIdentifier=DBinstance)
            print(response)
    except ClientError as e:
        print(e.response['Error']['Message']) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)