python - 使用 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 实例(运行和停止)。如何解决此错误以及如何确保它获取所有实例?
解决方案
如果实例没有任何标签,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)
推荐阅读
- javascript - 我无法让选择下拉菜单在我的页面上工作
- javascript - 本地状态的不变性和更新嵌套键
- angular - Angular jQuery Datatable 动态 ngModel 绑定值和服务器过滤或处理 - mData 错误管理
- html - 如何删除 div 之间的空白?
- python - 给定一张叠加图(A^B)和一张原图(A),如何计算另一张原图(B)
- r - Caret 特异性函数的错误输出
- sqlite - 从表末尾选择,直到选择包含多个有效值
- python - 缺少标题显示在情节中
- android - 为什么我的 ConstraintLayout 会这样工作?(东西交换位置)
- java - 如何将类的实例添加到 2D ArrayList