csv output for all ec2 instances in python

Viewed 493

I am trying to get all ec2 instances details in a csv file, followed another post "https://stackoverflow.com/questions/62815990/export-aws-ec2-details-to-xlsx-csv-using-boto3-and-python". But was having attribute error for Instances. So I am trying this:

 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)

For above I am having below error:

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'

I can see that this is not creating a dict output. Need suggestions on how can I create a dictionary of 'output' and publish that in a .csv file.

2 Answers

Since you are using DictWriter, your output should be:

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

Your function will also just keep overwriting your ec2_list.csv in each iteration, so you should probably re-factor it anyway.

A DictWriter - as the name would suggest - writes dicts i.e. dictionaries to a CSV file. The dictionary must have the keys that correspond to the column names. See the example in the docs I linked.

In the code you posted, you are passing output - a string - to the writerow function. Which will not work because, a string is not a dict.

You'll have to convert your output to something that writerow can accept, like a dict:

output = {'Instancename': Instancename, 'Id': Id ... }

And then try that.

Related