AWS RDS STOP & START

AWS RDS STOP & START

1. Step1: Create IAM Role and attach the below policy.


{

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

}


2. Create RDS start function-Python 2.7 and use the below script



import boto3

import logging

def lambda_handler(event,context):


logger = logging.getLogger()

logger.setLevel(logging.INFO)
#Boto3 connection
try:
rds=boto3.client('rds')
logger.info("Connected to rds client.")
except Exception as e:
logger.error("Unable to connect to rds client, Reason: "+str(e))
exit()

try:

logger.info("Starting rds instance...")
start_res=rds.start_db_instance(DBInstanceIdentifier='database-1')
logger.info("Started")
except Exception as e:
logger.error("Unable to start rds instance, Reason: "+str(e))

exit()

3. Create RDS stop function-Python 2.7 and use the below script


import boto3

import logging

def lambda_handler(event,context):


logger = logging.getLogger()

logger.setLevel(logging.INFO)
#Boto3 connection
try:
rds=boto3.client('rds')
logger.info("Connected to rds client.")
except Exception as e:
logger.error("Unable to connect to rds client, Reason: "+str(e))
exit()

try:

logger.info("Stoping rds instance...")
start_res=rds.stop_db_instance(DBInstanceIdentifier='database-1')
logger.info("Stopping")
except Exception as e:
logger.error("Unable to stop rds instance, Reason: "+str(e))

exit()

4. Final step to enable Cloud watch rule with Cron expression to auto stop and start the RDS.


COOL....





Comments