【发布时间】:2021-02-24 04:02:39
【问题描述】:
我正在尝试在 csv 文件中获取所有 ec2 实例详细信息,随后发布了另一篇文章“https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3和蟒蛇”。但是实例的属性错误。所以我正在尝试这个:
import boto3
import datetime
import csv
ec2 = boto3.resource('ec2')
for i in ec2.instances.all():
Id = i.id
State = i.state['Name']
Launched = i.launch_time
InstanceType = i.instance_type
Platform = i.platform
if i.tags:
for idx, tag in enumerate(i.tags, start=1):
if tag['Key'] == 'Name':
Instancename = tag['Value']
output = Instancename + ',' + Id + ',' + State + ',' + str(Platform) + ',' + InstanceType + ',' + str(Launched)
with open('ec2_list.csv', 'w', newline='') as csvfile:
header = ['Instancename', 'Id', 'State', 'Platform', 'InstanceType', 'Launched']
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
writer.writerow(output)
对于上面我有以下错误:
traceback (most recent call last):
File "list_instances_2.py", line 23, in <module>
writer.writerow(output)
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 155, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 148, in _dict_to_list
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'
我可以看到这不是在创建 dict 输出。需要有关如何创建“输出”字典并将其发布到 .csv 文件中的建议。
【问题讨论】:
标签: python amazon-web-services amazon-ec2