Skip to content

Instantly share code, notes, and snippets.

@benkehoe
Last active September 2, 2021 11:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save benkehoe/52fdbe425fcfc2675cd0ec2bb996257d to your computer and use it in GitHub Desktop.
Save benkehoe/52fdbe425fcfc2675cd0ec2bb996257d to your computer and use it in GitHub Desktop.
Template for running work in every account in an organization
import aws_assume_role_lib # https://github.com/benkehoe/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
# https://github.com/benkehoe/aws-sso-util/blob/master/lib/README.md
# 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}'
try:
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))
continue
# 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