首页 > 解决方案 > 使用 Python 按键值名称列出所有 AWS ec2

问题描述

我正在使用 python 列出所有 ec2 实例。目标是获取实例的名称,而不管实例状态如何。为此使用以下代码: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
        )

为此,我有以下输出:

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

它给出了实例的名称以及一个错误。我们有超过 1000 个 ec2 实例(运行和停止)。如何解决此错误以及如何确保它获取所有实例?

标签: pythonamazon-web-servicesamazon-ec2boto3

解决方案


如果实例没有任何标签,i.tags将为None​​. 所以你必须检查:

    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)

推荐阅读