in lambda/delete_old_snapshots_no_x_account_rds/lambda_function.py [0:0]
def lambda_handler(event, context):
delete_pending = 0
# Search for all snapshots
client = boto3.client('rds', region_name=DEST_REGION)
response = paginate_api_call(client, 'describe_db_snapshots', 'DBSnapshots')
# Filter out the ones not created automatically or with other methods
filtered_list = get_own_snapshots_no_x_account(PATTERN, response, DEST_REGION)
for snapshot in filtered_list.keys():
creation_date = get_timestamp(snapshot, filtered_list)
if creation_date:
snapshot_arn = filtered_list[snapshot]['Arn']
response_tags = client.list_tags_for_resource(
ResourceName=snapshot_arn)
if search_tag_created(response_tags):
difference = datetime.now() - creation_date
days_difference = difference.total_seconds() / 3600 / 24
# if we are past RETENTION_DAYS
if days_difference > RETENTION_DAYS:
# delete it
logger.info('Deleting %s. %s days old' %
(snapshot, days_difference))
try:
client.delete_db_snapshot(
DBSnapshotIdentifier=snapshot)
except Exception as e:
delete_pending += 1
logger.info('Could not delete %s (%s)' % (snapshot, e))
else:
logger.info('Not deleting %s. Only %s days old' %
(snapshot, days_difference))
else:
logger.info(
'Not deleting %s. Did not find correct tag' % snapshot)
else:
logger.debug(
'Not deleting %s. Did not find a timestamp' % snapshot)
if delete_pending > 0:
log_message = 'Snapshots pending delete: %s' % delete_pending
logger.error(log_message)
raise SnapshotToolException(log_message)