[英]csv output for all ec2 instances in python
我正在尝试获取 csv 文件中的所有 ec2 实例详细信息,然后是另一篇文章“https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and- Python”。 但是实例有属性错误。 所以我正在尝试这个:
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'
我可以看到这不是在创建字典 output。需要有关如何创建“输出”字典并将其发布在 .csv 文件中的建议。
由于您使用的是DictWriter
,因此您的output
应该是:
output = {
'Instancename': Instancename,
'Id': Id,
'State': State,
'Platform': str(Platform),
'InstanceType': InstanceType ,
'Launched': str(Launched)
}
您的 function 也将在每次迭代中继续覆盖您的ec2_list.csv
,因此无论如何您都应该重构它。
顾名思义,DictWriter
将dicts
(即字典)写入 CSV 文件。 字典必须具有与列名称相对应的键。 请参阅我链接的文档中的示例。
在您发布的代码中,您将output
- 一个字符串 - 传递给writerow
function。这是行不通的,因为 string 不是dict
。
您必须将output
转换为writerow
可以接受的内容,例如dict
:
output = {'Instancename': Instancename, 'Id': Id ... }
然后试试看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.