【问题标题】:Python BOTO3 script is not returning name inside the tagPython BOTO3 脚本未在标签内返回名称
【发布时间】:2021-12-13 09:50:15
【问题描述】:

我需要提取 AWS EC2 的名称、实例 ID、状态并将其导出到 csv。通过使用下面的代码,我得到了实例 ID 和状态。名称在标签内,我的标签中有多个键值,如下所示:

“标签”:[ { “价值”:“gggg”, “钥匙”:“bbbb” }, { “价值”:“rrrrrr”, “钥匙”:“eeeee” }, { “价值”:“uyyyutu”, “钥匙”:“hhhhhh” }, { “值”:“xxxxxxx”, “钥匙”:“姓名” }, { “价值”:“绿色”, “键”:“状态” }, { “价值”:“xxxxx”, “钥匙”:“yyyyy” } ]

如何从特定的 KEY=NAME 中获取名称。在使用以下代码时,我得到了标签中的所有值,但它没有给出特定的值。

import boto3
import csv

client = boto3.client('ec2')

response = client.describe_instances(
    Filters=[
        {
        'Name':'tag:STATE','Values':['GREEN']
        }
    ]
)

detail=[]

for Reservations in response["Reservations"]:
    for Instances in Reservations["Instances"]:
        detail.append({
            'ID':Instances['InstanceId'],
            'Status':Instances['State']['Name'],
            'Name':Instances['Tags']['Key'=='Name']['Value']
        })

header=['ID','Status','Name']
with open('EC2_Detail.csv','w') as file:
    writer=csv.DictWriter(file, fieldnames=header)
    writer.writeheader()
    writer.writerows(detail)


【问题讨论】:

    标签: python amazon-ec2 boto3


    【解决方案1】:

    试试:

    [x for x in Instances['Tags'] if x['Key'] == 'NAME'][0]['Value']
    

    如果没有为特定实例定义标签名称,这将中断。

    tag_names = [x for x in Instances['Tags'] if x['Key'] == 'NAME']
    if len(tag_names) > 0: name = tag_names[0]
    

    【讨论】:

    • 感谢@kgiannakakis 得到名称,但如果我尝试从标签中获取多个值,它会给出 indexerror: IndexError: list index out of range。代码在这里:`'Name':[x for x in Instances['Tags'] if x['Key'] == 'NAME'][0]['Value'], 'Env':[x for x in Instances['Tags'] if x['Key'] == 'ENVIRONMENT'][0]['Value'], 'Rel':[x for x in Instances['Tags'] if x['Key' ] == 'RELEASE'][0]['Value'], 'Data':[x for x in Instances['Tags'] if x['Key'] == 'data'][0]['Value '] `
    • 名称标签一直存在,所以在0处索引是安全的。对于其他标签键,您应该先检查是否有值。
    猜你喜欢
    • 2018-11-22
    • 2017-02-26
    • 2017-05-17
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多