4

I have a requirement that I want to list all the accounts and then write all the credentials in my ~/.aws/credentials file. Fir this I am using boto3 in the following way

import boto3

client = boto3.client('organizations')
response = client.list_accounts(
    NextToken='string',
    MaxResults=123
)
print(response)

This fails with the following error

botocore.exceptions.ClientError: An error occurred (ExpiredTokenException) when calling the ListAccounts operation: The security token included in the request is expired

The question is , which token is it looking at? And if I want information about all accounts what credentials should I be using in the credentials file or the config file?

user_mda
  • 18,148
  • 27
  • 82
  • 145

1 Answers1

12

You can use boto3 paginators and pages.

Get an organizations object by using an aws configuration profile in the master account:

session = boto3.session.Session(profile_name=master_acct)
client = session.client('sts')
org = session.client('organizations')

Then use the org object to get a paginator.

paginator = org.get_paginator('list_accounts')
page_iterator = paginator.paginate()

Then iterate through every page of accounts.

for page in page_iterator:        
    for acct in page['Accounts']:
        print(acct) # print the account

I'm not sure what you mean about "getting credentials". You can't get someone else's credentials. What you can do is list users, and if you want then list their access keys. That would require you to assume a role in each of the member accounts.

From within the above section, you are already inside a for-loop of each member account. You could do something like this:

id = acct['Id']
role_info = {
    'RoleArn': f'arn:aws:iam::{id}:role/OrganizationAccountAccessRole',
    'RoleSessionName': id
}


credentials = client.assume_role(**role_info)

member_session = boto3.session.Session(
    aws_access_key_id=credentials['Credentials']['AccessKeyId'],
    aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
    aws_session_token=credentials['Credentials']['SessionToken'],
    region_name='us-east-1'
)

However please note, that the role specified OrganizationAccountAccessRole needs to actually be present in every account, and your user in the master account needs to have the privileges to assume this role.

Once your prerequisites are setup, you will be iterating through every account, and in each account using member_session to access boto3 resources in that account.

Richard Quinn
  • 315
  • 1
  • 4
  • Thanks thats very useful , but running this gives me an error that I am not authorized to perform the "assumerole" operation – user_mda May 26 '20 at 14:25