我正在设置Lambda函数,以根据this script获取RDS实例的每日快照。我正在运行python3解释器。
import boto3
import datetime
def lambda_handler(event, context):
print("Connecting to RDS")
client = boto3.client('rds')
# Instance to backup
dbInstances = ['testdb']
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': 'Name',
'Value': 'dbInstace'
},
]
)
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=30):
print("Deleting snapshot id:", snapshot['DBSnapshotIdentifier'])
client.delete_db_snapshot(
DBSnapshotIdentifier=snapshot['DBSnapshotIdentifier']
)
该脚本适用于创建快照;但是每次运行时我都会收到此错误,因此我认为它不会正确删除快照。
'SnapshotCreateTime': KeyError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 29, in lambda_handler
createTs = snapshot['SnapshotCreateTime'].replace(tzinfo=None)
KeyError: 'SnapshotCreateTime'
Traceback (most recent call last):
File "/var/runtime/awslambda/bootstrap.py", line 226, in handle_event_request
result = request_handler(json_input, context)
File "/var/task/lambda_function.py", line 29, in lambda_handler
createTs = snapshot['SnapshotCreateTime'].replace(tzinfo=None)
KeyError: 'SnapshotCreateTime'
问题似乎特别在于这一行:
createTs = snapshot['SnapshotCreateTime'].replace(tzinfo=None)
为什么会这样?
答案 0 :(得分:1)
我怀疑您看到了KeyError,因为快照仍在进行中,并且尚未在返回的dict中填充SnapshotCreateTime。
在这种情况下,PercentProgress将小于100。
for snap in snapshots['DBSnapshots']:
if ('SnapshotCreateTime' in snap):
print snap['SnapshotCreateTime']
else:
print 'No create time available'
if ('PercentProgress' in snap):
print snap['PercentProgress']