Chat
Ask me anything
Ithy Logo

Comprehensive Guide to Retrieving Active AWS Accounts Using Boto3

Efficiently manage your AWS Organizational Units with Python

AWS Organizational Units

Key Takeaways

  • Efficient Traversal: Utilize recursive functions to navigate through root and sub-OUs seamlessly.
  • Pagination Handling: Implement paginators to manage large datasets without missing any accounts.
  • Active Account Filtering: Ensure only accounts with an 'ACTIVE' status are retrieved for accurate management.

Introduction

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.

Prerequisites

  • Python Installed: Ensure Python 3.6 or later is installed on your machine.
  • Boto3 Library: Install the Boto3 library, which is the AWS SDK for Python.
  • AWS Credentials: Configure AWS credentials with sufficient permissions to access AWS Organizations.
  • Permissions: The AWS user or role should have the following permissions:
    • organizations:ListAccountsForParent
    • organizations:ListChildren
    • organizations:ListOrganizationalUnitsForParent

Setting Up Your Environment

Installing Boto3

Start by installing the Boto3 library using pip:

pip install boto3
    

Configuring AWS Credentials

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.


Implementing the Python Program

Overview

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.

Detailed Code Explanation


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 Breakdown

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.

Key Components

  • Boto3 Organizations Client: Facilitates interaction with AWS Organizations.
  • Pagination: Handles large result sets by iterating through paginated responses.
  • Recursive Traversal: Efficiently navigates through nested OUs to ensure comprehensive account retrieval.
  • Status Filtering: Ensures only accounts with an 'ACTIVE' status are included in the final list.

Running the Script

Execution Steps

  1. Replace Root OU ID: Update the 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.
  2. Execute the Script: Run the script in your Python environment:
    python get_active_accounts.py
                
  3. Review Output: The script will output a list of active AWS accounts with their IDs, names, and associated email addresses.

Sample Output

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
    

Error Handling

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.


Best Practices

  • Secure Credentials: Avoid hardcoding AWS credentials. Use IAM roles or environment variables to manage credentials securely.
  • Logging: Implement detailed logging to track the script's execution and troubleshoot potential issues.
  • Modular Code: Structure the code into modular functions to enhance readability and maintainability.
  • Testing: Test the script in a controlled environment before deploying it in a production setting to ensure it behaves as expected.
  • Version Control: Use version control systems like Git to manage changes to your scripts effectively.

Conclusion

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.


References


Last updated January 18, 2025
Ask Ithy AI
Download Article
Delete Article