Created
October 27, 2023 19:37
-
-
Save atheiman/e405d8d17bbb3a5c9687f6f7442e3edf to your computer and use it in GitHub Desktop.
boto3 run api calls in multiple regions of multiple accounts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import boto3 | |
import botocore | |
partition = 'aws' | |
regions = ['us-east-1', 'us-west-2'] | |
skip_master_acct = True | |
organizations = boto3.client('organizations') | |
sts = boto3.client('sts') | |
def process_acct(acct_id): | |
creds = sts.assume_role( | |
RoleArn=f"arn:{partition}:iam::{acct_id}:role/OrganizationAccountAccessRole", | |
RoleSessionName="crossacctaction", | |
)['Credentials'] | |
assumed_role_sts = boto3.client( | |
'sts', | |
aws_access_key_id=creds['AccessKeyId'], | |
aws_secret_access_key=creds['SecretAccessKey'], | |
aws_session_token=creds['SessionToken'], | |
) | |
print(assumed_role_sts.get_caller_identity()['Arn']) | |
for region in regions: | |
assumed_role_ec2 = boto3.client( | |
'ec2', | |
region_name=region, | |
aws_access_key_id=creds['AccessKeyId'], | |
aws_secret_access_key=creds['SecretAccessKey'], | |
aws_session_token=creds['SessionToken'], | |
) | |
for pg in assumed_role_ec2.get_paginator('describe_instances').paginate(): | |
for r in pg['Reservations']: | |
for i in r['Instances']: | |
print(acct_id, region, i['InstanceId']) | |
master_acct_id = organizations.describe_organization()['Organization']['MasterAccountId'] | |
for pg in organizations.get_paginator('list_accounts').paginate(): | |
for acct in pg['Accounts']: | |
if skip_master_acct and acct['Id'] == master_acct_id: | |
continue | |
process_acct(acct['Id']) | |
print() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment