1
votes

I need to create a list of instances, the AMI that was used to create it, and the creation date of the AMI.

This is the Python (boto3) code I am using:

import boto3
import datetime
import sys

profile = (sys.argv[1])
boto3.setup_default_session(profile_name=profile)

ec2 = boto3.resource('ec2')
instances = ec2.instances.all()
images = ec2.images.filter(Owners=['self'])

for i in instances:
    a = i.id
    b = i.state['Name']
    c = i.instance_type
    if i.platform == 'windows':
        d = i.platform
    else:
        d = 'linux'
    e = i.private_ip_address
    f = i.image_id
    g = i.image.creation_date.strftime("%Y-%m-%d %H:%M:%S")
    print('{}   {}  {}  {}  {}  {}'.format(a, b, c, d, e, f, g))

But this is the error I am getting; pertaining to the creation_date call:

Traceback (most recent call last): File "C:\bin\TestAMI.py", line 23, in g = i.image.creation_date.strftime("%Y-%m-%d %H:%M:%S") File "C:\Python27\lib\site-packages\boto3\resources\factory.py", line 345, in property_loader return self.meta.data.get(name) AttributeError: 'NoneType' object has no attribute 'get'

How can get the creation date of the available AMIs in use?

1
Line 345 refers to shows: return self.meta.data.get(name)jmoorhead
Is there a boto3 import resource factory I need to import?jmoorhead
Also the script code requires a profile name to be passed to it. I use 'default'.jmoorhead
Note that you will also need to handle the case of the AMI having been deleted. It is possible to delete an AMI even if running (or stopped) instances were launched from it, because once an instance is initially launched, it has no further dependency on the AMI. If this information is important, you might want this script to also persist the attributes for all AMIs in some kind of database for future reference.Michael - sqlbot

1 Answers

0
votes

Here is an example of handling AMIs that have been deleted, as per @sqlbot:

import boto3

for i in boto3.resource('ec2').instances.all():
    print(' '.join([
        i.id,
        i.state['Name'],
        i.instance_type,
        i.platform or 'Linux',
        i.private_ip_address,
        getattr(i.image, 'creation_date', '')
    ]))