簡體   English   中英

AWS Lambda 無法獲取 EC2 AZ 詳細信息

[英]AWS Lambda failing to fetch EC2 AZ details

我正在嘗試使用 Python3.9 創建 lambda 腳本,它將返回 AWS 帳戶中的總 ec2 服務器、它們的狀態和詳細信息。 我的一些代碼片段是 -

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 詳細信息,代碼工作正常。如果我創建一個新的 function,其中只有 AZ 參數,則返回所有 AZ。 不明白為什么它在上述代碼中失敗。

在 python 中,最好的做法是使用 get 方法從列表或字典中獲取值來處理異常。

AvailibilityZone 實際上存在於 Placement dict 中,而不是實例詳細信息中。 您可以從下面的 boto 3 文檔參考中檢查整個響應結構

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('Placement', dict()).get('AvailabilityZone')}")
            print(f"\nInstanceId: {instance_details.get('InstanceId')}")
            print(f"\nInstanceType: {instance_details.get('InstanceType')}")

問題是,響應describe_instances可用性區域不在第一級實例字典中(在您的情況下為instance_details )。 可用區在Placement字典下,所以你需要的是

print(f"AvailabilityZone: {instance_details.get('Placement', dict()).get('AvailabilityZone')}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM