【问题标题】:AWS Lambda: Boto3 "errorType": "KeyError"AWS Lambda:Boto3“errorType”:“KeyError”
【发布时间】:2022-01-23 08:36:12
【问题描述】:

下面是我试图从 describe_volumes 中提取 SnapshotId 的简单代码。但是,我得到一个没有太多信息的 KeyError 。请让我知道我做错了什么,谢谢

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

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

在上面的代码中,我得到以下错误:

{
  "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"
  ]
}

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 aws-lambda boto3


    【解决方案1】:

    “describe_volumes”方法的响应语法为:

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

    因此,当您尝试读取 SnapshotId 属性时,它不起作用,因为它不在根级别。考虑到它是一个卷列表,您可以对其进行迭代并实现您需要的逻辑。例如:

        response_describe_volumes = ec2.describe_volumes(VolumeIds=['vol-xxxxxxxxxxx'])
    
        for volume in response_describe_volumes['Volumes']:
            print(volume['SnapshotId'])
            #TODO
    

    参考:

    Boto3 describe_volumes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 2020-08-21
      • 2020-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2016-03-08
      相关资源
      最近更新 更多