python - python中所有ec2实例的csv输出
问题描述
我正在尝试在 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'
我可以看到这不是在创建 dict 输出。需要有关如何创建“输出”字典并将其发布到 .csv 文件中的建议。
解决方案
由于您使用的是DictWriter
,您output
应该是:
output = {
'Instancename': Instancename,
'Id': Id,
'State': State,
'Platform': str(Platform),
'InstanceType': InstanceType ,
'Launched': str(Launched)
}
您的函数也将在每次迭代中继续覆盖您的函数ec2_list.csv
,因此无论如何您都应该重新考虑它。
推荐阅读
- ssl - Google Cloud Platform 上的 SSL 证书
- java - 如何在Spring中从@Autowired List<>的每个bean中获取@Qualifier
- mysql - 使用外键删除 MySQL 多表
- php - 使用 getlog() 执行的最后一个查询不会显示在 cake2php 中
- html - NodeJS 未检测或删除抓取的 HTML 中的问号 (?)
- azure-databricks - 将 Databricks 数据帧写入 BLOB 存储
- mysql - 如何在 mysql 的表中获取每个日期的唯一 SKU 计数(自学问题)
- java - Maven包含依赖删除一个
- javascript - 将对象数组附加到 HTML 文件中
- java - List all subpackages of a package (when their classes are loaded dynamically)