Search code examples
amazon-web-servicesaws-lambdaboto3

AWS Lambda failing to fetch EC2 AZ details


I am trying to create lambda script using Python3.9 which will return total ec2 servers in AWS account, their status & details. Some of my code snippet is -

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'])

On ruunning this code i get error - enter image description here

If I comment AZ details, code works fine.If I create a new function with only AZ parameter in it, all AZs are returned. Not getting why it fails in above mentioned code.


Solution

  • In python, its always a best practice to use get method to fetch value from list or dict to handle exception.

    AvailibilityZone is actually present in Placement dict and not under instance details. You can check the entire response structure from below boto 3 documentation Reference

    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')}")