Home > Software engineering >  Iterating through describe_instances() to print key & value boto3
Iterating through describe_instances() to print key & value boto3

Time:11-03

I am currently working on a python script to print pieces of information on running EC2 instances on AWS using Boto3. I am trying to print the InstanceID, InstanceType, and PublicIp. I looked through Boto3's documentation and example scripts so this is what I am using:

import boto3    

ec2client = boto3.client('ec2')
response = ec2client.describe_instances()

for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        instance_id = instance["InstanceId"]
        instance_type = instance["InstanceType"]
        instance_ip = instance["NetworkInterfaces"][0]["Association"]

print(instance)
print(instance_id)
print(instance_type)
print(instance_ip)

When I run this, "instance" prints one large block of json code, my instanceID, and type. But I am getting an error since adding NetworkInterfaces.

instance_ip = instance["NetworkInterfaces"][0]["Association"]

returns:

Traceback (most recent call last):
File "/Users/me/AWS/describeInstances.py", line 12, in <module>
instance_ip = instance["NetworkInterfaces"][0]["Association"]
KeyError: 'Association'

What am I doing wrong while trying to print the PublicIp?

Here is the structure of NetworkInterfaces for reference: describe_instances()

The full Response Syntax for reference can be found here (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances)

CodePudding user response:

Association man not always may be present. Also an instance may have more then one interface. So your working loop could be:

for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        instance_id = instance["InstanceId"]
        instance_type = instance["InstanceType"]
        #print(instance)
        print(instance_id, instance_type)
        for network_interface in instance["NetworkInterfaces"]:
            instance_ip = network_interface.get("Association", "no-association")
            print(' -', instance_ip)
  • Related