diff --git a/infrastructure/global/stacksets/inf-org-crossaccount/test-cross-org.py b/infrastructure/global/stacksets/inf-org-crossaccount/test-cross-org.py new file mode 100755 index 00000000..f9586017 --- /dev/null +++ b/infrastructure/global/stacksets/inf-org-crossaccount/test-cross-org.py @@ -0,0 +1,56 @@ +import boto3 +from botocore.exceptions import ClientError + +# --- SET THESE TO MATCH YOUR TERRAFORM --- +CROSS_ACCOUNT_ROLE_NAME = "OrganizationAdminAccessRole" +TARGET_REGION = "us-east-1" + +def test_connectivity(): + # 1. Initialize the Organizations client from Management Account + org_client = boto3.client('organizations') + sts_client = boto3.client('sts') + + print(f"Starting connectivity test using role: {CROSS_ACCOUNT_ROLE_NAME}\n") + print(f"{'Account Name':<25} | {'Account ID':<15} | {'Status'}") + print("-" * 55) + + # 2. Page through all accounts in the Org + paginator = org_client.get_paginator('list_accounts') + for page in paginator.paginate(): + for account in page['Accounts']: + # Skip accounts that aren't active (suspended/pending) + if account['State'] != 'ACTIVE': + continue + + acc_id = account['Id'] + acc_name = account['Name'] + role_arn = f"arn:aws:iam::{acc_id}:role/{CROSS_ACCOUNT_ROLE_NAME}" + + try: + # 3. Attempt to assume the role + response = sts_client.assume_role( + RoleArn=role_arn, + RoleSessionName="ConnectivityTestSession" + ) + + # 4. Use temporary credentials to create a target session + creds = response['Credentials'] + target_session = boto3.Session( + aws_access_key_id=creds['AccessKeyId'], + aws_secret_access_key=creds['SecretAccessKey'], + aws_session_token=creds['SessionToken'] + ) + + # 5. Perform a "whoami" call in the target account + target_sts = target_session.client('sts') + identity = target_sts.get_caller_identity() + + print(f"{acc_name[:25]:<25} | {acc_id:<15} | ✅ Success") + + except ClientError as e: + # Catch failures (e.g., role hasn't finished deploying or trust policy issue) + error_code = e.response['Error']['Code'] + print(f"{acc_name[:25]:<25} | {acc_id:<15} | ❌ Failed ({error_code})") + +if __name__ == "__main__": + test_connectivity()