I want to use AWS Lambda to stop an Amazon Relational Database Service (Amazon RDS) DB instance for more than the seven-day duration.
Short description
By default, you can stop an Amazon RDS DB instance for up to seven days at a time. After seven days, the instance restarts so that it doesn't miss any maintenance updates.
To stop your instance for more than seven days, use Lambda with Amazon EventBridge to automate the start and stop workflow around your maintenance window.
Note: For an alternative resolution, see How do I use Step Functions to stop an Amazon RDS instance for more than 7 days?
Resolution
Note: This article provides one possible solution to use tags and Lambda functions to stop an RDS DB instance. You can update the implementation and timing to meet your requirements.
Configure IAM permissions
To allow Lambda to start and stop your instance and retrieve information on the instance, create an AWS Identity and Access Management (IAM) policy.
Complete the following steps:
- Open the IAM console.
- In the navigation pane, choose Policies.
- Choose Create policy.
- In the Policy editor section, choose the JSON option.
- Delete the existing content and enter the following 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": "*"
}
]
}
Note: It's a best practice to restrict the resource scope or use tag-based conditions for least privilege access. To restrict resource scope, replace the value for Resource with a value based on your environment.
- Resolve any security warnings or errors, and then choose Next.
- On the Review and create page, for Policy name, enter a name for your policy.
- (Optional) For Description, enter a description for your policy.
- Choose Create policy.
For more information, see Creating policies using the JSON editor.
Create an IAM role and attach the required policies
To allow Lambda to assume the permissions you created, create an IAM role and attach the required policies.
Complete the following steps:
- Open the IAM console.
- In the navigation pane, choose Roles.
- Choose Create role.
- For Trusted entity type, choose AWS service.
- For Service or use case, choose Lambda, and then choose the Lambda use case.
- Choose Next.
- Search for and choose the custom policy that you created in the preceding section.
- Search for and choose the AWSLambdaBasicExecutionRole managed policy.
- Choose Next.
- For Role name, enter a name for the role.
- (Optional) For Description, enter a description for the role.
- Choose Create role.
For more information, see Creating a role for an AWS service (console).
Add tags for DB instances
Complete the following steps:
- Open the Amazon RDS console.
- In the navigation pane, choose Databases.
- Choose the name of the DB instance that you want to tag.
- In the details section, scroll down to the Tags section.
- Choose Add.
- For Tag key, enter autostart.
- For Value, enter yes, and then choose Add to save your changes.
- Choose Add again.
- For Tag key, enter autostop.
- For Value, enter yes, and then choose Add to save your changes.
For more information, see Tagging Amazon RDS resources.
Create a Lambda function to start or stop the tagged DB instances
Complete the following steps:
- Open the Lambda console.
- In the navigation pane, choose Functions.
- Choose Create function.
- Choose Author from scratch.
- Under Basic information, do the following:
For Function name, enter the name of your function.
For Runtime, choose Python 3.14.
For Architecture, keep the default selection of x86_64.
- Expand Change default execution role.
- For Execution role, choose Use an existing role.
- For Existing role, choose the IAM role that you created.
- Choose Create function.
- Choose the Code tab.
- In the Code source editor, delete the existing code. Enter one of the following code examples based on the action that you want to perform:
Start tagged DB instances:
import boto3
rds = boto3.client('rds')
def lambda_handler(event, context):
#Start DB Instances
dbs = rds.describe_db_instances()
for db in dbs['DBInstances']:
#Check if DB instance stopped. Start it if eligible.
if (db['DBInstanceStatus'] == 'stopped'):
try:
GetTags=rds.list_tags_for_resource(ResourceName=db['DBInstanceArn'])['TagList']
for tags in GetTags:
#if tag "autostart=yes" is set for instance, start it
if(tags['Key'] == 'autostart' and tags['Value'] == 'yes'):
result = rds.start_db_instance(DBInstanceIdentifier=db['DBInstanceIdentifier'])
print ("Starting instance: {0}.".format(db['DBInstanceIdentifier']))
except Exception as e:
print ("Cannot start instance {0}.".format(db['DBInstanceIdentifier']))
print(e)
if __name__ == "__main__":
lambda_handler(None, None)
-or-
Stop tagged DB instances:
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)
Note: These code examples demonstrate a basic approach. You can update the code or create a new implementation to use tag-based logic to start or stop your RDS DB instance.
- Choose Deploy.
- Choose the Configuration tab, choose General configuration, and then choose Edit.
- Under Timeout, enter the following values:
For min, enter 0.
For sec, enter 10.
- Choose Save.
Test the Lambda functions
For tagged DB instances that are in the Stopped state, complete the following steps:
- Open the Lambda console.
- Choose the function that you created to start the DB instances.
- Choose the Test tab.
- For Event name, enter the name of your test event.
- Choose Save, and then choose Test.
Create the schedule
You can create EventBridge rules to set up a schedule. For example, if your weekly maintenance window for the tagged DB instances is Sunday 22:00–22:30, then create two EventBridge rules. Create one rule to automatically start the DB instance 30 minutes before the maintenance window begins. Create another rule to automatically stop the DB instance 30 minutes after the maintenance window ends.
To create a rule that automatically starts the DB instance before the maintenance window, complete the following steps:
- Open the Lambda console.
- Choose the function that you created to start the DB instances.
- Under Function overview, choose Add trigger.
- Choose EventBridge (CloudWatch Events), and then choose Create a new rule.
- For Rule name, enter the name of the rule.
- For Schedule expression, enter a cron expression for the automated schedule. For example, cron(30 21 ? * SUN *).
- Choose Add.
To create a rule that automatically stops the DB instance after the maintenance window, follow the preceding steps. Update the rule name and the cron expression for the stop schedule.
Related information
Implementing DB instance stop and start in Amazon RDS
Field Notes: Stopping an automatically started database instance with Amazon RDS
How do I stop an Aurora cluster for longer than 7 days?