How to stop and start RDS instance in AWS using Python

I’ve been working on a project that requires us to shutdown and startup our development databases to save costs.. I’ve come up with a python script to perform the tasks.

This could be modified to your own requirements.

Here is the code:

import boto3

#   Author: Mark Young
#   Date:   19th December 2017
#   Detail: Stop and start RDS instances based on Tags
#   Note:   Aurora databases are currently not supported for shutdown and startup methods.
#
#   Audit:  1.0 - M.Y. Original
#



Tag = 'MYSQLTEST'
Key = 'Application'

client = boto3.client('rds')
response = client.describe_db_instances()

for resp in response['DBInstances']:
   db_instance_arn = resp['DBInstanceArn']


   response = client.list_tags_for_resource(ResourceName=db_instance_arn)
   for tags in response['TagList']:
       if tags['Key'] == str(Key) and tags['Value'] == str(Tag):
           status = resp['DBInstanceStatus']
           InstanceID = resp['DBInstanceIdentifier']
           print(InstanceID)
           #print(status)
           if status == 'available':
               print("shutting down %s " % InstanceID)
               client.stop_db_instance(DBInstanceIdentifier= InstanceID)
               #print ("Do something with it : %s" % db_instance_arn)
           elif status == 'stopped':
                print("starting up %s " % InstanceID)
                client.start_db_instance(DBInstanceIdentifier= InstanceID)
           else:
                print("The database is " + status + " status!")

2 thoughts on “How to stop and start RDS instance in AWS using Python”

  1. Hi ,

    Whether above script loops through and stops the db instance.
    For me , it checks only first db instance, i used the same code as above.

    Reply

Leave a Comment

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