In this tutorial, we are going to setup a Lambda function to take daily database backups of our RDS database. We will be using Python 2.7 code to define our Lambda function.
So first, go ahead and navigate to the Lambda service in your AWS console and create a blank Lambda Function.
We can configure the trigger later, so leave the next page as it is and click `Next`.
In the next step, we will give a name and description for our Lambda function. We will also set the `Runtime` as `Python 2.7` since our code is written for `Python 2.7`.
Next step is the python function. Use the code given below, but remember to modify it to match your RDS instance name.
The above code will create new snapshots of the DB instance `lambdainst` while deleting the existing manual backups of the same DB instance older than 7 days.
In the next section, you can leave the `Handler` field with the default value. Howerver, we will have to create a new IAM role with privileges to create and delete RDS snapshots. So, for the `Role` filed choose `Create a custom Role`.
IN the resulting page, set `IAM Role` as `Create new IAM Role` and specify a `Role Name`. Then add the following policy.
This role will give privileges for logging, creating snapshots and deleting snapshots. Make sure you change the RDS region and other resource field values as per your setup.
After clicking `Allow`, you will be retured to the Lamba creation page and the `Role` value will have changed to `Choose an Existing Role` with `Existing Role` as our newly created role.
The Lambda function is now complete. You can leave the rest of the fields with the default values and create the function.
Now that we have created the function, we have to schedule it to run daily. For this, click the `Triggers` tab and add a trigger.
Set the trigger type as `CloudWatch Events` with rule as `Create a new rule`. Specify a rule name and description then Choose `Schedule Expression`. In the `Schedule Expression` file enter the following, cron(0 1 * * ? *). This will trigger the Lambda function at 1:00 AM every day. If you wish to change the schedule, you can reconfigure the cron value by the following URL.
Schedule Expressions for Rules
That's it. The Lambda function to take daily snapshots of our RDS database is ready. You can test it immediately using the `Test` button and verify everything is working fine.