import boto3
accounts = ['1111111111', '2222222222']
# session = boto3.Session(profile_name='cache')
sts = boto3.client('sts') #assumes you have a default profile set
for id in accounts:
role_arn = f'arn:aws:iam::11111111:role/sucacheaccess'
creds = sts.assume_role(RoleArn=role_arn, RoleSessionName='some-name')
session = boto3.Session(aws_access_key_id=creds['AccessKeyId'],aws_secret_access_key=['SecretAccessKey'])
ec2 = session.client('ec2', region_name='eu-west-2')
response = ec2.describe_instances()
import datetime
import csv
time = datetime.datetime.now().strftime ('%Y-%m-%d-%H-%M-%S')
filename_describe_instances = ('ec2_inventory_me-south-1_' + time + '.csv')
fieldnames = ['Instance_Name','ImageId', 'InstanceId', 'InstanceType', 'Availability_Zone', 'Platform', 'PrivateIpAddress','PublicIpAddress', 'State', 'SubnetId','VpcId', 'Environment', 'AccountId']
with open(filename_describe_instances, 'w', newline='') as csvFile:
writer = csv.writer(csvFile, dialect='excel')
writer.writerow(fieldnames)
for Reserv in response['Reservations']:
for Insta in Reserv['Instances']:
instance_imageid = Insta.get('ImageId', 'NULL')
instance_InstanceId = Insta.get('InstanceId', 'NULL')
instance_InstanceType = Insta.get('InstanceType', 'NULL')
instance_Availability_Zone = Insta['Placement'].get('AvailabilityZone', 'NULL')
instance_Platform = Insta.get('Platform', 'Linux')
instance_Private_IP = Insta.get('PrivateIpAddress', 'NULL')
instance_Public_IP = Insta.get('PublicIpAddress', 'NULL')
instance_State = Insta['State'].get('Name', 'NULL')
instance_Subnet = Insta.get('SubnetId', 'NULL')
instance_VPCID = Insta.get('VpcId', 'NULL')
instance_OwnerId = Reserv.get('OwnerId', 'NULL')
tags_list = []
for n in Insta.get('Tags', 'NULL'):
if n.get('Key', 'NULL') == 'Name':
instance_Name = n.get('Value', 'NULL')
if n.get('Key', 'NULL') == 'Environment':
instance_Environment = n.get('Value', 'NULL')
raw = [instance_Name,
instance_imageid,
instance_InstanceId,
instance_InstanceType,
instance_Availability_Zone,
instance_Platform,
instance_Private_IP,
instance_Public_IP,
instance_State,
instance_Subnet,
instance_VPCID,
instance_OwnerId]
writer.writerow(raw)
for o in raw:
o = 'NULL'
raw = []
csvFile.close()
I followed the below article and couldn't resolve the credentials to fetch the information from multiple aws accounts, What is missing in the code?
How generate EC2 inventory from multiple AWS Account using python boto3