Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active August 16, 2024 21:15
Show Gist options
  • Save atheiman/7ead826019c82fdde72d99f1831c326a to your computer and use it in GitHub Desktop.
Save atheiman/7ead826019c82fdde72d99f1831c326a to your computer and use it in GitHub Desktop.
Run boto3 in a loop across all organization member AWS accounts
import json
import boto3
import os
import traceback as tb
if boto3.session.Session().region_name.startswith("us-gov-"):
partition = "aws-us-gov"
regions = ["us-gov-west-1", "us-gov-east-1"]
else:
partition = "aws"
regions = ["us-east-1", "us-west-2"]
orgs = boto3.client("organizations")
sts = boto3.client("sts")
org = orgs.describe_organization()["Organization"]
def handler(event, context):
accounts = []
for pg in orgs.get_paginator("list_accounts").paginate():
for account in pg['Accounts']:
if account['Status'] == "ACTIVE" and account["Id"] != org["MasterAccountId"]:
accounts.append(account)
exceptions = []
for account in accounts:
try:
handle_account(account)
except Exception as e:
print("ERROR - Exception processing account:", account['Name'], account['Id'])
tb.print_exc()
exceptions.append(e)
if exceptions:
print("ERROR - Encountered error in one or more accounts:")
raise (Exception(exceptions))
def handle_account(account):
print("Processing account:", account['Name'], account['Id'])
# get short-term credentials in other account
creds = sts.assume_role(
RoleArn=f"arn:{partition}:iam::{account['Id']}:role/OrganizationAccountAccessRole",
RoleSessionName=os.environ.get('AWS_LAMBDA_FUNCTION_NAME', 'crossacctaccess')[:64],
)["Credentials"]
# create a boto3 session using credentials in other account
session = boto3.Session(
aws_access_key_id=creds["AccessKeyId"],
aws_secret_access_key=creds["SecretAccessKey"],
aws_session_token=creds["SessionToken"],
)
# get source servers from each region
for region in regions:
handle_region(session, account, region)
def handle_region(session, account, region):
print("Processing account region:", account['Name'], account['Id'], region)
ec2 = session.client("ec2", region_name=region)
for pg in ec2.get_paginator("describe_vpcs").paginate():
for vpc in pg["Vpcs"]:
print(json.dumps(vpc, default=str))
if __name__ == "__main__":
handler({}, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment