- Newest
- Most votes
- Most comments
If you are operating multiple accounts in an AWS Organization I'd suggest using Config for this because you can easily query Config to see many different types of resources across all account. The resources you can access are listed here and IAM Users are in that list.
That said, you can also do this by running some code. The example below iterates through all accounts in an Organization but you could also pass in a list of account ids instead. I originally wrote this to get a list of VPCs and IP address ranges in each VPC but it is not difficult to modify it to query IAM Users instead.
import boto3
import sys
crossAccountRoleName = 'NetworkRole'
org = boto3.client('organizations')
sts = boto3.client('sts')
def processAccount(ec2, credentials):
identity = sts.get_caller_identity()
regionList = ec2.describe_regions()['Regions']
for region in regionList:
if credentials:
ec2Region = boto3.client('ec2',
aws_access_key_id=credentials['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
aws_session_token=credentials['Credentials']['SessionToken'],
region_name=region['RegionName'])
else:
ec2Region = boto3.client('ec2')
vpcList = ec2Region.describe_vpcs().get('Vpcs', [])
for vpc in vpcList:
print(f'{identity["Account"]},{region["RegionName"]},{vpc["VpcId"]},{vpc["CidrBlock"]}')
try:
orgDetails = org.describe_organization()
except:
ec2 = boto3.client('ec2')
processAccount(ec2, None)
sys.exit(0)
accountPaginator = org.get_paginator('list_accounts')
accountIterator = accountPaginator.paginate()
for object in accountIterator:
for account in object['Accounts']:
if account['Id'] == orgDetails['Organization']['MasterAccountId']:
ec2 = boto3.client('ec2')
processAccount(ec2, None)
else:
targetRoleArn = f'arn:aws:iam::{account["Id"]}:role/{crossAccountRoleName}'
try:
credentials = sts.assume_role(RoleArn=targetRoleArn,
RoleSessionName='VPCNetworkScanner')
except Exception as e:
print(f'STS assume_role failed: {e} for account {account["Id"]}')
continue
ec2 = boto3.client('ec2',
aws_access_key_id=credentials['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
aws_session_token=credentials['Credentials']['SessionToken'])
processAccount(ec2, Credentials)
You would need to create cross account roles and then assume the role in each account and query the list of users.
However, what you should be doing is to have all users in one AWS account and manage users from here. This way your problem wouldn’t exist. Users would just assume roles in said accounts.
