简体   繁体   English

Python BOTO3 脚本未在标签内返回名称

[英]Python BOTO3 script is not returning name inside the tag

I need to extract the name, instance id, state of AWS EC2 and export it to csv.我需要提取 AWS EC2 的名称、实例 ID、状态并将其导出到 csv。 By using the below code I got the instance id and state.通过使用下面的代码,我得到了实例 ID 和状态。 The name is inside the tags and I am having multiple key-value in my tags like below:名称在标签内,我的标签中有多个键值,如下所示:

"Tags": [ { "Value": "ggggg", "Key": "bbbb" }, { "Value": "rrrrrr", "Key": "eeeee" }, { "Value": "uyyyutu", "Key": "hhhhhh" }, { "Value": "xxxxxxx", "Key": "NAME" }, { "Value": "GREEN", "Key": "STATE" }, { "Value": "xxxxx", "Key": "yyyyy" } ] "标签": [ { "Value": "ggggg", "Key": "bbbb" }, { "Value": "rrrrrr", "Key": "eeeee" }, { "Value": "uyyyutu", "Key": "hhhhhh" }, { "Value": "xxxxxxxx", "Key": "NAME" }, { "Value": "GREEN", "Key": "STATE" }, { "Value": "xxxxx", "Key": "yyyyy" } ]

How can I get the name from particular KEY=NAME.如何从特定的 KEY=NAME 获取名称。 While using the following code I am getting all values in the tags it is not giving particular value.在使用以下代码时,我获取了标签中的所有值,但并未给出特定值。

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)


尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM