Last active
June 11, 2019 09:44
-
-
Save adamantnz/ec89ad535ec584d8b80bea6c8cdee648 to your computer and use it in GitHub Desktop.
lambda: create dynamodb table backups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date, datetime, timedelta | |
import json | |
import boto3 | |
from botocore.exceptions import ClientError | |
import os | |
ddbRegion = os.environ['AWS_DEFAULT_REGION'] | |
now = datetime.now().strftime("-%Y-%m-%d-%H-%M-%S") | |
backupRetention = 7 | |
def lambda_handler(event, context): | |
try: | |
ddb = boto3.client('dynamodb', region_name=ddbRegion) | |
tables = ddb.list_tables()['TableNames'] | |
for table in tables: | |
backupName = table + now | |
ddb.create_backup(TableName=table, BackupName=backupName) | |
lowerDate = datetime.now() - timedelta(days=365) | |
upperDate = datetime.now() - timedelta(days=backupRetention) | |
responseLatest = ddb.list_backups(TableName=table, | |
TimeRangeLowerBound=datetime(lowerDate.year, lowerDate.month, lowerDate.day), | |
TimeRangeUpperBound=datetime(upperDate.year, upperDate.month, upperDate.day)) | |
latestBackupCount = len(responseLatest['BackupSummaries']) | |
print(table, ': Backup', backupName, 'created. Number backups <', | |
upperDate, 'to delete:', latestBackupCount) | |
if latestBackupCount != 0: | |
for record in responseLatest['BackupSummaries']: | |
backupArn = record['BackupArn'] | |
ddb.delete_backup(BackupArn=backupArn) | |
print('Deleted backup:', backupArn) | |
else: | |
None | |
except ClientError as e: | |
print(e) | |
except ValueError as ve: | |
print('error:', ve) | |
except Exception as ex: | |
print(ex) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment