1
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

sk4ever
  • 31
  • 4
  • 1
    Please fix your code's indentation. – jarmod Jul 30 '22 at 14:09
  • code is updated. What else to be checked. – sk4ever Jul 30 '22 at 15:35
  • If the indentation currently shown is what you're running, then you're only calling `ec2.describe_instances()` once because it's outside the for loop. Your for loop is also (incorrectly?) assuming the same IAM role every time, regardless of account number. These are very basic bugs that should be obvious to you when debugging. – jarmod Jul 30 '22 at 15:41
  • @jarmod i am newbie in python scripting and just exploring the existing script to achieve the output. I tried with assume role and i get only trusting account information not trusted. I want to pull trusted and trusting account details. If possible could you align the script please. – sk4ever Jul 30 '22 at 16:33
  • 1
    Here is an [example](https://stackoverflow.com/a/57035462/271415) of how to get STS credentials and make API calls. Do this in a loop, once per AWS account of interest. – jarmod Jul 30 '22 at 17:20
  • @jarmod i already looped with multiple account but credentials didn't work, can u take a look what is wrong in the code? – sk4ever Jul 31 '22 at 04:18

0 Answers0