I need to extract the name, instance id, state of AWS EC2 and export it to csv. By using the below code I got the instance id and state. 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" } ]
How can I get the name from particular 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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.