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.


import boto3
import json
from datetime import datetime, timedelta, tzinfo

def lambda_handler(event, context):
print("Connecting to RDS")
client = boto3.client('rds')

#Creating new snapshots
#DBInstanceIdentifier - The name of your database instance
#DBSnapshotIdentifier - the name of your snapshot. Please make sure to add the date with it to distinguish between snapshots.

print("RDS snapshot backups stated at %s...\n" % datetime.now())
client.create_db_snapshot(
DBInstanceIdentifier='lambdadbinst',
DBSnapshotIdentifier='lambdadbinst-%s' % datetime.now().strftime("%y-%m-%d-%H"),
Tags=[
{
'Key': 'Lambda',
'Value': 'DB'
},
]
)


#Deleting old snapshots
#Timedelta - modify this value as per how long you wish to retain a single backup
for snapshot in client.describe_db_snapshots(DBInstanceIdentifier='lambdadbinst', SnapshotType='manual')['DBSnapshots']:
if snapshot['SnapshotCreateTime'].replace(tzinfo=None) < (datetime.now() - timedelta(days=7)):
print "Deleting snapshot id:", snapshot['DBSnapshotIdentifier']
client.delete_db_snapshot(
DBSnapshotIdentifier=snapshot['DBSnapshotIdentifier']
)


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.


{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"rds:AddTagsToResource",
"rds:DeleteDBSnapshot"
],
"Resource": "arn:aws:rds:us-east-1::snapshot:*"
},
{
"Effect": "Allow",
"Action": [
"rds:ListTagsForResource",
"rds:CreateDBSnapshot"
],
"Resource": "arn:aws:rds:us-east-1:*"
},
{
"Effect": "Allow",
"Action": [
"rds:DescribeDBSnapshots"
],
"Resource": "*"
}
]
}


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.

Comments (3)

  • Jhonathon Doe
  • Posted on 29 Jun, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  • Jhonathon Doe
  • Posted on 29 Jun, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

  • Jhonathon Doe
  • Posted on 29 Jun, 2017

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Leave Us A Comment