Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Template for running work in every account in an organization
import aws_assume_role_lib #
account_role_name = "YOUR_ACCOUNT_ROLE_NAME_HERE" # TODO: put your role name here
management_account_session = boto3.Session()
# if you're using AWS SSO in your management account and there's a specific role for this work, you could use aws-sso-lib
# management_account_session = aws_sso_lib.get_boto3_session(start_url, sso_region, management_account_id, management_role_name, region=sso_region)
orgs = management_account_session.client('organizations')
# if you need to do a specific OU, there's list_accounts_for_parent
# if you need it to be recursive into sub-OUs, you'll need to use list_organizational_units_for_parent as well
# and at that point you'll probably want to fold some of this up into functions
paginator = orgs.get_paginator('list_accounts')
failed = []
i = 0
for response in paginator.paginate():
for account in response['Accounts']:
i += 1
account_id = account['Id']
account_name = account['Name']
print(f'processing account {i}: {account_id} {account_name}')
account_role_arn = f'arn:aws:iam::{account_id}:role/{account_role_name}'
account_session = aws_assume_role_lib.assume_role(management_account_session, account_role_arn)
except Exception as e:
failed.append((account_id, account_name, e))
# TODO: your work in the account goes here using account_session
# e.g., account_session.client('sts').get_caller_identity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment