Python BOTO3 脚本未返回标签内的名称
Python BOTO3 script is not returning name inside the tag
我需要提取 AWS EC2 的名称、实例 ID、状态并将其导出到 csv。通过使用下面的代码,我得到了实例 ID 和状态。名称在标签内,我的标签中有多个键值,如下所示:
“标签”:[
{
“值”:“ggggg”,
“键”:“bbbb”
},
{
“值”:“rrrrrr”,
“关键”:“eeeeee”
},
{
"值": "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)
尝试:
[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]
我需要提取 AWS EC2 的名称、实例 ID、状态并将其导出到 csv。通过使用下面的代码,我得到了实例 ID 和状态。名称在标签内,我的标签中有多个键值,如下所示:
“标签”:[ { “值”:“ggggg”, “键”:“bbbb” }, { “值”:“rrrrrr”, “关键”:“eeeeee” }, { "值": "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)
尝试:
[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]