Creating an AWS scheduler to control the start and stop time of your database achieves a reduction of the cost that comes with holding up active resources. You don’t need all your databases running 24/7, and you manually choosing when to stop the DB is not an ideal long-term solution. Fortunately, you can schedule the activity of your database without manual interference.
Unlike the very simple option of stopping your DB through the AWS console, this process would be a bit more detailed. The added advantage of a flexible AWS scheduler and not having to worry about the DB starting automatically a week later makes the small process more worth it.
First, we must create a policy for the IAM role to be attached to.
AWS has a visual editor for creating the policy but you can just copy-paste the JSON code below for your convenience.
The IAM role will allow making service requests which are necessary for scheduling the AWS RDS stop instance, it also grants access to CloudWatch logs.
Before creating a Lambda function, make sure your region is the same as the region where you created the DB instance.
Since you can control instances in multiple regions, choosing the right region is necessary for the function to work. You could use the same function later on for your instances hosted on multiple regions.
You’ll be able to receive the AWS RDS stop instance name and the Availability Zone from the administrator.
Enter the following information on the window:
You will find an ARN resource created for the Lambda function in the top right corner. The resource allows the function to access the GetFunctionConfiguration Lambda API and the AWS lambda environment variable.
Now, return to the ManualScheduleRDS role and click on Add Inline Policy.
Assign the ARN on the JSON code and then click Save.
AWS Lambda will now appear as a Resource in the function.
Add the following Python code to the function.
The line of code responsible for stopping the RDS is rds.stop_db_instance.
The AWS Lambda environment variable, DBInstanceName is held by the variable DBInstance. This environment variable is the key-value pair that will let you use this Lambda function in other environments like Dev, QA or Prod.
Configure the function
Save and you’re done! Now you have a Lambda function to stop your RDS instance. If you receive a message saying “Instance<> is not in an available state”, then your DB is not started.
The process for setting up the Start function is identical to the Stop function, with most of the changes going to the names and some lines of code.
Now that you have the two Lambda functions at your beck and call, you just need to determine when to invoke them. For this, you will have to set a rule on AWS CloudWatch.
Your scheduled RDS Instance is now ready to go, you need not concern yourself with stopping and restarting your instances anymore.