Home > Blockchain >  Python Boto3 is not printing all region ec2 detail
Python Boto3 is not printing all region ec2 detail

Time:11-17

I need to get ec2 detail from all regions and need to generate a csv. So stored the regions in an array and tried, but only the last region details are getting displayed.

import boto3
import csv

ec2=boto3.client(service_name='ec2')

region=[]
for each_region in ec2.describe_region()['Regions']:
    region.append(each_region['RegionName'])

for each_region in region:
    client = boto3.client('ec2',region_name=each_region)

    result = []
    response = ec2.describe_instances(
        InstanceIds=[
            'i-xxxxxxxxxxxxxxxxx'
        ]).get('Reservations')

    for item in response:
        for each in item['Instances']:
            result.append({
                'ImageId': each['ImageId'],
                'InstanceType': each['InstanceType'],
                'PublicIp': each['PublicIpAddress'],
                'PrivateIp': each['PrivateIpAddress']
            })


    header = ['ImageId', 'InstanceType', 'PublicIp', 'PrivateIp']
    with open('ec2-details.csv', 'w') as file:
        writer = csv.DictWriter(file, fieldnames=header)
        writer.writeheader()
        writer.writerows(result)

CodePudding user response:

You should restructure the code to:

  • initialize the results before the region loop
  • write the results after the region loop

Note: I removed the placeholder list of InstanceIds from the call to describe_instances because I did not see anywhere in your code where you were populating this list. Add it back, if needed.

Here's an example:

result = []

for each_region in region:
    client = boto3.client('ec2',region_name=each_region)
    
    response = ec2.describe_instances().get('Reservations')

    for item in response:
        for each in item['Instances']:
            result.append({
                'ImageId': each['ImageId'],
                'InstanceType': each['InstanceType'],
                'PublicIp': each['PublicIpAddress'],
                'PrivateIp': each['PrivateIpAddress']
            })

header = ['ImageId', 'InstanceType', 'PublicIp', 'PrivateIp']
with open('ec2-details.csv', 'w') as file:
    writer = csv.DictWriter(file, fieldnames=header)
    writer.writeheader()
    writer.writerows(result)
  • Related