Hi I have a dict inside list, want to write the dict to csv.
Using boto3 ec2 client, describe_instance() function. I want to those tags to a csv.
Code I tried,
def write_csv(mode,field_name,value):
with open(report, mode, newline='') as f:
writer = csv.writer(f)
client = session.client('ec2')
response = client.describe_instances(
Filters=[
{
'Name': 'instance-id',
'Values': [
'string',
],
},
],
)
tags=response['Reservations'][0]['Instances'][0]['Tags']
for tag in tags:
field_names=tag['Key']
values=tag['Value']
write_csv('a',field_names,values)
Output I got:
Column A | Column B |
---|---|
tag1 | value1 |
tag2 | value2 |
tag3 | value3 |
Excepted output
tag1 | tag2 | tag3 |
---|---|---|
value1 | value2 | value3 |
I added the instanceId as requested.
If you are willing to import pandas, this should work:
import pandas as pd
save_path = 'my_csv_name.csv'
client = session.client('ec2')
response = client.describe_instances(
Filters=[
{
'Name': 'instance-id',
'Values': [
'string',
],
},
],
)
resp = response['Reservations'][0]['Instances'][0]
tags.append({'Key':'InstanceId','Value':resp['InstanceId']}
df = pd.DataFrame(resp['Tags'])
df.set_index('Key').T.to_csv(save_path)