Home > Blockchain >  Delete specific prefixed RDS manual snapshots which are 7 days old
Delete specific prefixed RDS manual snapshots which are 7 days old

Time:02-16

I would need some help in deleting the RDS manual snapshots. We create RDS Snapshots daily, but I want to delete snapshots which are 7 days. At the moment it only deletes one snapshot. I want it to delete all those snapshot which starts with the name rds-test-instance which are 7 days old.

import boto3


def snap_check(text):
    result = text.startswith('from-rds-test-instance')
    return result


client = boto3.client('rds')
DB = 'rds-test-instance'

#-----Define Lambda function-----#
def lambda_handler(event, context):
    snapshots = client.describe_db_snapshots(
        DBInstanceIdentifier=DB,
        SnapshotType='manual'
        )

    for i in snapshots['DBSnapshots']:
        if snap_check(str(i['DBSnapshotIdentifier'])):
            print(i['DBSnapshotIdentifier'])

I have now edited the code and it prints out the list perfectly. I just now need to put the delete bit in the above code. So that it can delete snapshots which are older then 7 days. Can anyone help please

CodePudding user response:

This is how i achieved the whole scenario. If anyone else is looking

    import boto3
    import datetime
    from datetime import datetime, timezone
    from datetime import timedelta

    today = (datetime.today()).date()
    now = today - timedelta(days=7)

    def snap_check(text):
        result = text.startswith('from-rds-test-instance-')
        return result


        client = boto3.client('rds')
        DB = 'rds-test-instance'

#-----Define Lambda function-----#
def lambda_handler(event, context):
    snapshots = client.describe_db_snapshots(
        DBInstanceIdentifier=DB,
        SnapshotType='manual'
        )
    print('Following DB Snapshots will be deleted')
    for i in snapshots['DBSnapshots']:
        if snap_check(str(i['DBSnapshotIdentifier'])) and i ["SnapshotCreateTime"].date() < now:
            print(i['DBSnapshotIdentifier'])
            #del_response = client.delete_db_snapshot(
            #    DBSnapshotIdentifier=i['DBSnapshotIdentifier']
            #    )

CodePudding user response:

Your code should:

  • Call describe_db_snapshots()
  • Loop through the list of returned Snapshot and:
    • Check the value for SnapshotCreateTime
    • If it is older than 7 days, call delete_db_snapshot()
  • Related