-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit c86a340
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
56 changes: 56 additions & 0 deletions
56
infrastructure/global/stacksets/inf-org-crossaccount/test-cross-org.py
This file contains 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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() |