DEV Community

ChungWei Wei
ChungWei Wei

Posted on • Originally published at kmp.tw on

[AWS] RDS Will Start DB Instance After Stopped Seven Days Automation

Situation

AWS RDS Will Start DB Instance After You Stopped DB Instance Seven Days Automation For That Doesnโ€™t Fall Behind Any Required Maintenance Updates.

Ref

How To

  • ### You Can Delete DB Instance After Take Snapshot, If You Want Use That DB, You Can Restore DB Instance From Snapshot.
  • ### You Can Write Lambda Function With Schedule To Stop DB Instance.

Write Lambda ~

Create IAM & Lambda

IAM Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "rds:StartDBCluster",
                "rds:StopDBCluster",
                "rds:ListTagsForResource",
                "rds:DescribeDBInstances",
                "rds:StopDBInstance",
                "rds:DescribeDBClusters",
                "rds:StartDBInstance"
            ],
            "Resource": "*"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Lambda Code For Stop Tagged DB Instance (Python)

import boto3
rds = boto3.client('rds')

def lambda_handler(event, context):

    #Stop DB instances
    dbs = rds.describe_db_instances()
    for db in dbs['DBInstances']:
        #Check if DB instance is not already stopped
        if (db['DBInstanceStatus'] == 'available'):
            try:
                GetTags=rds.list_tags_for_resource(ResourceName=db['DBInstanceArn'])['TagList']
                for tags in GetTags:
                #if tag "autostop=yes" is set for instance, stop it
                    if(tags['Key'] == 'autostop' and tags['Value'] == 'yes'):
                        result = rds.stop_db_instance(DBInstanceIdentifier=db['DBInstanceIdentifier'])
                        print ("Stopping instance: {0}.".format(db['DBInstanceIdentifier']))
            except Exception as e:
                print ("Cannot stop instance {0}.".format(db['DBInstanceIdentifier']))
                print(e)

if __name__ == "__main__":
    lambda_handler(None, None)

Enter fullscreen mode Exit fullscreen mode

In Lambda Schedule

cron(00 00 ? * SUN *)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)