首页 > 解决方案 > 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 文件中的建议。

标签: pythonamazon-web-servicesamazon-ec2

解决方案


由于您使用的是DictWriter,您output应该是:

            output = {
                'Instancename': Instancename,
                'Id': Id, 
                'State': State, 
                'Platform': str(Platform), 
                'InstanceType': InstanceType , 
                'Launched': str(Launched)
            }

您的函数也将在每次迭代中继续覆盖您的函数ec2_list.csv,因此无论如何您都应该重新考虑它。


推荐阅读