简体   繁体   中英

AWS Lambda: Boto3 "errorType": "KeyError"

Below is the simple code where I'm trying to pull SnapshotId from describe_volumes. However, I get a KeyError with not much information to go off of. Please let me know what I'm doing wrong, thank you

import boto3
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    
    snapshot_id = ec2.describe_volumes(VolumeIds=['vol-xxxx'])
    print(snapshot_id['SnapshotId'])

In the above code, I get the following error:

{
  "errorMessage": "'SnapshotId'",
  "errorType": "KeyError",
  "requestId": "6b99ce8b-092e-49b8-89b3-72381129e9cc",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 7, in lambda_handler\n    print(snapshot_id['SnapshotId'])\n"
  ]
}

The response synthax for 'describe_volumes' method is:

{
    'Volumes': [
        {
            'Attachments': [
                .
                .
                ,
            ],
            'AvailabilityZone': 'string',
            'SnapshotId': 'string',
            .
            .
            .
        },
    ],
    'NextToken': 'string'
}

So when you attempt to read the SnapshotId attribute it does not work because it is not on the root level. Considering it is a list of volumes you can iterate it and implement the logic that you need. For example:

    response_describe_volumes = ec2.describe_volumes(VolumeIds=['vol-xxxxxxxxxxx'])

    for volume in response_describe_volumes['Volumes']:
        print(volume['SnapshotId'])
        #TODO

Reference:

Boto3 describe_volumes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM