简体   繁体   中英

Iterating through describe_instances() to print key & value boto3

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: 描述实例()

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 )

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM