I'm starting using boto3 and I wonder how I can get an inventory of all ec2 instances in all regions with custom attributes and put it to CSV file. For the single region it looks simple:
import boto3
import jmespath
import csv
client = boto3.client('ec2')
response = client.describe_instances()
myData = jmespath.search("Reservations[].Instances[].[NetworkInterfaces[0].OwnerId, InstanceId, InstanceType, State.Name, Placement.AvailabilityZone, PrivateIpAddress, PublicIpAddress, KeyName, [Tags[?Key=='Name'].Value] [0][0]]", response)
myFile = open('inventory.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
But I can't figure out how to achieve a similar result for all regions. I've tried something like this:
all_regions = client.describe_regions()
RegionList = []
for r in all_regions['Regions']:
RegionList.append(r['RegionName'])
for r in RegionList:
client = boto3.client('ec2', region_name = r)
response = client.describe_instances()
myData = jmespath.search("Reservations[].Instances[].[NetworkInterfaces[0].OwnerId, InstanceId, InstanceType, State.Name, Placement.AvailabilityZone, PrivateIpAddress, PublicIpAddress, KeyName, [Tags[?Key=='Name'].Value] [0][0]]", response)
myFile = open('inventory.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
But I'm getting just an empty list.