Created
November 2, 2024 02:21
-
-
Save lordjabez/c9b9f796385bb663f5688e91c109c326 to your computer and use it in GitHub Desktop.
Do a thing across all AWS accounts in an organization
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 | |
orgs_client = boto3.client('organizations') | |
sts_client = boto3.client('sts') | |
management_account_id = sts_client.get_caller_identity()['Account'] | |
def get_active_accounts(): | |
params = {} | |
accounts = [] | |
while True: | |
response = orgs_client.list_accounts(**params) | |
accounts.extend(response['Accounts']) | |
if 'NextToken' in response: | |
params['NextToken'] = response['NextToken'] | |
else: | |
return [a for a in accounts if a['Status'] == 'ACTIVE'] | |
def get_sts_credentials(account): | |
account_id = account['Id'] | |
role_arn = f'arn:aws:iam::{account_id}:role/OrganizationAccountAccessRole' | |
response = sts_client.assume_role(RoleArn=role_arn, RoleSessionName='assume-org-role') | |
credentials = { | |
'aws_access_key_id': response['Credentials']['AccessKeyId'], | |
'aws_secret_access_key': response['Credentials']['SecretAccessKey'], | |
'aws_session_token': response['Credentials']['SessionToken'], | |
} | |
return credentials | |
def get_boto3_session(account): | |
credentials = get_sts_credentials(account) | |
return boto3.session.Session(**credentials) | |
def do_a_thing(session): | |
pass | |
accounts = get_active_accounts() | |
for account in accounts: | |
print(account['Name']) | |
if account['Id'] != management_account_id: | |
session = get_boto3_session(account) | |
else: | |
session = boto3.session.Session() | |
do_a_thing(session) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment