2
votes

I am trying to create/delete Snapshot of my AWS RDS through function of AWS Lamda (python 3.6), but I don't know where I am doing wrong, this function also delete Snapshot from 7 days old, so anyone can suggest me on this

import boto3
import datetime

def lambda_handler(event, context):
    print("Connecting to RDS")
    client = boto3.client('rds')
    dbInstances = ['magento-live']

    for dbInstance in dbInstances:
        print("RDS snapshot backups started at %s...\n" % datetime.datetime.now())

        client.create_db_snapshot(
            DBInstanceIdentifier=dbInstance,
            DBSnapshotIdentifier=dbInstance+'{}'.format(datetime.datetime.now().strftime("%y-%m-%d-%H")),
            Tags=[
                {
                    'Key': 'NI',
                    'Value': 'NIRDS'

                },
            ]
        )

        for snapshot in client.describe_db_snapshots(DBInstanceIdentifier=dbInstance, MaxRecords=50)['DBSnapshots']:
            createTs = snapshot['SnapshotCreateTime'].replace(tzinfo=None)
            if createTs < datetime.datetime.now() - datetime.timedelta(days=7):
                print("Deleting snapshot id:", snapshot['DBSnapshotIdentifier'])
                client.delete_db_snapshot(
                    DBSnapshotIdentifier=snapshot['DBSnapshotIdentifier']
                )

But always I am getting below error

    {
  "errorMessage": "An error occurred (InvalidParameterValue) when calling the CreateDBSnapshot operation: The specified instance is a member of a cluster and a snapshot cannot be created directly. Please use the CreateDBClusterSnapshot API instead.",
  "errorType": "ClientError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      19,
      "lambda_handler",
      "'Value': 'NIRDS'"
    ],
    [
      "/var/runtime/botocore/client.py",
      312,
      "_api_call",
      "return self._make_api_call(operation_name, kwargs)"
    ],
    [
      "/var/runtime/botocore/client.py",
      605,
      "_make_api_call",
      "raise error_class(parsed_response, operation_name)"
    ]
  ]
}
1
As per the error message looks like you need to use CreateDBClusterSnapshot - Aron
Yes that I can understand, so should I use client.create_db_cluster_snapshot instead of client.create_db_snapshot, next to print - user1325743
I am having Aurora - user1325743

1 Answers

0
votes

Aron is right. You have use a different method (that applies to aurora cluster and not a DB instance).

Here is a lambda function that worked for me:

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

print("RDS snapshot backups stated at %s...\n" % datetime.datetime.now())
client.create_db_cluster_snapshot(
    DBClusterIdentifier='enter-your-cluster-name-her', 
    DBClusterSnapshotIdentifier='enter-your-cluster-name-here-%s' % datetime.datetime.now().strftime("%y-%m-%d-%H"),
    Tags=[
        {
            'Key': 'ENV',
            'Value': 'dev'
        },
    ]
)