0
votes

I am using python to list all ec2 instances. Goal is get the name of the instances regardless of instance state. Using below code for this: import boto3

ec2 = boto3.resource('ec2')

for i in ec2.instances.all():

    for idx, tag in enumerate(i.tags):
            if tag['Key'] == 'Name':
              instancename = tag['Value']
    print( idx, instancename
        )

For this I am having below output:

1 bob_instance
1 sampleinstance2
6 devteam-ec2
13 qateam-ec2
16 security-solutions
15 testinstances-123
Traceback (most recent call last):
  File "just_tags_1.py", line 7, in <module>
    for idx, tag in enumerate(i.tags):
TypeError: 'NoneType' object is not iterable

It's giving Name of the instances as well as an error. We have more than 1000 ec2 instances (both running and stopped). How can I resolve this error and how to make sure it fetched all instances?

1

1 Answers

1
votes

If the instance does not have any tags, i.tags will be None. So you have to check for that:

    ec2 = boto3.resource('ec2')
    
    for i in ec2.instances.all():
        if i.tags:
            for idx, tag in enumerate(i.tags):
                if tag['Key'] == 'Name':
                    instancename = tag['Value']
                    print(idx, instancename)