Managing multiple AWS accounts within an organization can be complex, especially when dealing with numerous Organizational Units (OUs). Automating the retrieval of active accounts within root OUs and their sub-OUs can significantly streamline administrative tasks. This guide provides a comprehensive Python program using the Boto3 library to efficiently fetch all active AWS accounts within a specified root OU or any nested sub-OUs.
organizations:ListAccountsForParentorganizations:ListChildrenorganizations:ListOrganizationalUnitsForParentStart by installing the Boto3 library using pip:
pip install boto3
Configure your AWS credentials using the AWS CLI or by setting environment variables. Using the AWS CLI is recommended for ease of use:
aws configure
Provide your AWS Access Key ID, AWS Secret Access Key, default region, and output format when prompted.
The Python program leverages Boto3's Organizations client to interact with AWS Organizations. It employs recursive functions to traverse through the OU hierarchy, retrieves active accounts, and handles pagination to ensure complete data retrieval.
import boto3
from typing import List, Dict
def get_active_accounts_in_ou(org_client, parent_id: str) -> List[Dict]:
"""
Retrieves all active accounts within a specified parent OU or root.
Args:
org_client: Boto3 Organizations client.
parent_id (str): The ID of the parent OU or root.
Returns:
List[Dict]: A list of dictionaries containing active account details.
"""
active_accounts = []
# Initialize paginator for listing accounts under the parent OU/root
paginator = org_client.get_paginator('list_accounts_for_parent')
for page in paginator.paginate(ParentId=parent_id):
for account in page['Accounts']:
if account['Status'] == 'ACTIVE':
active_accounts.append({
'AccountId': account['Id'],
'AccountName': account['Name'],
'Email': account['Email']
})
return active_accounts
def get_all_active_accounts(org_client, parent_id: str) -> List[Dict]:
"""
Recursively retrieves all active accounts within a root OU or any nested sub-OUs.
Args:
org_client: Boto3 Organizations client.
parent_id (str): The ID of the root OU or sub-OU.
Returns:
List[Dict]: A consolidated list of all active accounts within the hierarchy.
"""
all_active_accounts = []
# Retrieve active accounts in the current OU
all_active_accounts.extend(get_active_accounts_in_ou(org_client, parent_id))
# Initialize paginator for listing child OUs
paginator = org_client.get_paginator('list_children')
for page in paginator.paginate(ParentId=parent_id, ChildType='ORGANIZATIONAL_UNIT'):
for child in page['Children']:
# Recursively retrieve active accounts in child OUs
all_active_accounts.extend(get_all_active_accounts(org_client, child['Id']))
return all_active_accounts
def main():
"""
Main function to execute the retrieval of active AWS accounts.
"""
# Initialize the Organizations client
org_client = boto3.client('organizations')
# Specify the Root OU ID or target sub-OU ID
root_ou_id = 'r-xxxx' # Replace with your actual Root OU ID
try:
# Fetch all active accounts within the specified OU hierarchy
active_accounts = get_all_active_accounts(org_client, root_ou_id)
# Display the retrieved active accounts
print("Active AWS Accounts:")
for account in active_accounts:
print(f"Account ID: {account['AccountId']}, Name: {account['AccountName']}, Email: {account['Email']}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
| Function | Description |
|---|---|
get_active_accounts_in_ou |
Retrieves all active accounts directly under a specified parent OU or root. |
get_all_active_accounts |
Recursively retrieves active accounts from the root OU and all nested sub-OUs. |
main |
Initializes the Organizations client, specifies the root OU ID, and triggers the retrieval process. |
root_ou_id variable in the main function with your actual Root OU ID. You can retrieve the Root OU ID from the AWS Management Console or by using the list_roots API.python get_active_accounts.py
Active AWS Accounts:
Account ID: 123456789012, Name: Development, Email: dev-team@example.com
Account ID: 234567890123, Name: Production, Email: ops-team@example.com
Account ID: 345678901234, Name: Testing, Email: test-team@example.com
The script includes basic error handling to catch and display exceptions that may occur during execution, such as insufficient permissions or invalid OU IDs. Ensure that the AWS credentials used have the necessary permissions and that the specified OU IDs are correct to prevent errors.
Automating the retrieval of active AWS accounts within organizational units is essential for efficient cloud management. By leveraging Python's Boto3 library, administrators can seamlessly navigate through complex OU structures, ensuring that all active accounts are accounted for and managed appropriately. This guide provides a robust foundation for implementing such automation, promoting better organization and resource management within AWS.