skip to Main Content

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.

2

Answers


  1. 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')}")
    
    Login or Signup to reply.
  2. The problem is that in response of describe_instances availability zone is not in first level of instance dictionary (in your case instance_details). Availability zone is under Placement dictionary, so what you need is

    print(f"AvailabilityZone: {instance_details.get('Placement', dict()).get('AvailabilityZone')}")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search