【问题标题】:AWS Lambda failing to fetch EC2 AZ detailsAWS Lambda 无法获取 EC2 AZ 详细信息
【发布时间】:2023-01-23 00:49:01
【问题描述】:

我正在尝试使用 Python3.9 创建 lambda 脚本,它将返回 AWS 帐户中的总 ec2 服务器、它们的状态和详细信息。我的一些代码 sn-p 是 -

def lambda_handler(event, context):
    client = boto3.client("ec2")
    #s3 = boto3.client("s3")

    # fetch information about all the instances
    status = client.describe_instances()
    
    for i in status["Reservations"]:
        instance_details = i["Instances"][0]
        if instance_details["State"]["Name"].lower() in ["shutting-down","stopped","stopping","terminated",]:
            print("AvailabilityZone: ", instance_details['AvailabilityZone'])
            print("\nInstanceId: ", instance_details["InstanceId"])
            print("\nInstanceType: ",instance_details['InstanceType'])

运行此代码时出现错误 -

如果我注释 AZ 详细信息,代码工作正常。如果我创建一个新函数,其中只有 AZ 参数,则返回所有 AZ。不明白为什么它在上述代码中失败。

【问题讨论】:

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


    【解决方案1】:

    在 python 中,最好的做法是使用 get 方法从列表或字典中获取值来处理异常。

    由于 AvailabilityZone 不存在于您从 boto3 获得的响应中,因此会引发错误。 我建议打印整个回复。 并在 jsonviewer 中检查它以查找 AvailabilityZone 是否存在。

    def lambda_handler(event, context):
        client = boto3.client("ec2")
        #s3 = boto3.client("s3")
    
        # fetch information about all the instances
        status = client.describe_instances()
        
        for i in status["Reservations"]:
            instance_details = i["Instances"][0]
            if instance_details["State"]["Name"].lower() in ["shutting-down","stopped","stopping","terminated",]:
                print(f"AvailabilityZone: {instance_details.get('AvailabilityZone')}")
                print(f"
    InstanceId: {instance_details.get('InstanceId')}")
                print(f"
    InstanceType: {instance_details.get('InstanceType')}")
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2021-07-06
      • 2019-07-02
      • 2017-12-26
      • 2019-02-18
      相关资源
      最近更新 更多