AWS allows us to keep any RDS in stopped state only for 7 days. If the RDS instance remains stopped after 7th day, it will get automatically started. Let’s say, you have Oracle RDS, or MySQL RDS, or any other RDS that you wanna setup auto stop functionality.
To keep an RDS instance in stopped state for more than 7 days, you can use the following solution using AWS Lambda function.
First we need to setup AWS lambda function with CloudWatch event as trigger. This CloudWatch event should trigger the Lambda function on every 6 days. And function should does the following:
Step 1: Check if the instance is running. If the instance is already started, stop it. Function ends here. It will not continue with step 2.
If the instance is not started, then the function continues to the next step.
Step 2: Detach the Elastic IP and start the instance. Once it is started and active, stop the RDS instance and re-associate the Elastic IP.
By this way, we can keep the RDS instance in stopped state. Other way of doing the same is by checking only if the instance has got automatically started. If it is started, then the lambda function will stop it.
You can also be able to stop the AWS RDS (MySQL) instance for longer duration. RDS instance gets restarted after 7 days. You need to setup this in order to make sure that the instance stays is not running and you won’t get billed for it.
Schedule lambda function to stop RDS
To trigger the lambda function we can use API gateway, file event from S3 or any other event sources. However, in our case, we need to set it run once 6 days. The reason for setting the number of days as 6 rather than 7 itself is to avoid starting of RDS.
For scheduling the lambda function on time basis, you need to add and configure CloudWatch as a trigger which will fire an event to execute or invoke our lambda function.
Note that the function requires necessary permission which we will set shortly.
Also you need to create a role to give permission for CloudWatch in order to trigger your function.
Read here about how to check RDS state after stopping from the lambda. I have written about a technique which is written as an answer to one of top discussion for the same topic in StackOverflow.
Also, I have included code samples and design diagram on the above post.
Why AWS auto starts RDS after 7 days?
AWS RDS, like any other service, consumes heavy physical and logical entities to provide service to their customers. Allowing an RDS instance in stopped state will incur more cost than those compared to an EC2 instance.
Hence AWS will keep it auto-started if it was stopped for more than continuous 7 days. Or you can delete the instance if no more required, taking a snapshot if necessary.
How useful was this post?
Click on a star to rate it!
Average rating 3.7 / 5. Vote count: 3
We are sorry that this post was not useful for you!
Let us improve this post!
Thanks for your feedback!