AWS Lambda:RDS 快照 - KeyError

AWS Lambda: RDS Snapshot - KeyError

我正在设置一个 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)

为什么会这样?

我怀疑您看到了 KeyError,因为快照仍在进行中,并且 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']