简体   繁体   中英

How to print ec2 Instance Image tags using boto3?

I am trying to print the AWS EC2 Instances' details using boto3 . Following is what i have tried so far. I am able to print all required fields except the Image related info.

import boto3

session=boto3.session.Session()
ec2_re=session.resource(service_name='ec2',region_name='us-east-1')

for i in ec2_re.instances.all():
    pvt_ip=i.private_ip_address
    i_type=i.instance_type
    os=i.platform
    i_arch=i.architecture
    tags=i.tags
    hypv=i.hypervisor
    iid=i.id
    i_id=i.instance_id
    i_state=i.state['Name']
    i_img=i.image

    print(i.image)
    print(type(i.image))

    for tag in i_img.tags:
        if tag['Key'] == 'Description':
            print(img.description,img.image_type,img.name,img.platform,tag['Value'])    

When i execute this, i am getting the following error:

ec2.Image(id='ami-1234c567a')
<class 'boto3.resources.factory.ec2.Image'>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-5e1745dafc4> in <module>
     33     print(type(i.image))
     34 
---> 35     for tag in i_img.tags:
     36         if tag['Key'] == 'Description':
     37             print(img.description,img.image_type,img.name,img.platform,tag['Value'])

C:\ProgramData\Anaconda3\lib\site-packages\boto3\resources\factory.py in property_loader(self)
    343                             self.__class__.__name__))
    344 
--> 345             return self.meta.data.get(name)
    346 
    347         property_loader.__name__ = str(snake_cased)

AttributeError: 'NoneType' object has no attribute 'get'

This works fine when i separately initialize the image class. But, this way i won't be able to fetch other info like i am getting in the above code snipped where i am getting error.

img = ec2_re.Image(id='ami-197cf68fl53990')
for tag in img.tags:
    if tag['Key'] == 'Description':
        print(img.description,img.image_type,img.name,img.platform,tag['Value'])

Can someone suggest how i can fix this?

The problem is being caused by deprecated images .

For example, Windows images are deprecated when a newer version is made available. While the image object can be retrieved, it does not actually contain any information (name, tags, etc). Thus, it is not possible to display any information about it.

You will need to add a try statement to catch such situations and skip-over the deprecated image.

import boto3

ec2_resource = boto3.resource('ec2')

# Display AMI information for all instances
for instance in ec2_resource.instances.all():
    image = instance.image

    # Handle situation where image has been deprecated
    try:
        tags = image.description
    except:
        continue

    if image.tags is None:
        description_tag = ''
    else:
        description_tag = [tag['Value'] for tag in image.tags if tag['Name'] == 'Description'][0]

    print(image.description, image.image_type, image.name, image.platform, description_tag) 

Use client instead of resource :

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

You can find the structure of the response here: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances

I guess it returns all the data which you need.

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