List AWS Accounts by Organizational Unit (OU) Name


As a developer or administrator working with AWS Organizations, you may often need to figure out which AWS account belongs to which Organizational Unit (OU).

Unfortunately, AWS does not provide a direct way to search for accounts using the OU name; instead, it requires you to use the OU ID, which is not very developer-friendly.

In this how-to guide, we will show you how to find AWS accounts by their OU name. This can be particularly useful as it allows you to locate AWS accounts in a more intuitive way.

How to filter AWS Accounts by Organizational Unit Name

Before you can start, you’re required to have done the following prerequisites before you can run the Python script on your AWS management account.

  • Have an AWS multi-account setup with AWS Organizations enabled
  • Must be using Organizational Units in AWS Organizations
  • Install the AWS CLI and configure an AWS profile
  • Setting up the Python Environment

If you’ve already done this, you can proceed to step 3.

1. Install AWS CLI and configure an AWS profile

The AWS CLI is a command line tool that allows you to interact with AWS services in your terminal.

Depending on if you’re running LinuxmacOS, or Windows the installation goes like this:

# macOS install method:
brew install awscli

# Windows install method:
wget https://awscli.amazonaws.com/AWSCLIV2.msi
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi

# Linux (Ubuntu) install method:
sudo apt install awscli

In order to access your AWS account with the AWS CLI, you first need to configure an AWS Profile. There are 2 ways of configuring a profile:

  • Access and secret key credentials from an IAM user
  • AWS Single Sign-on (SSO) user

In this article, I’ll briefly explain how to configure the first method so that you can proceed with running the python script on your AWS account.

If you wish to set up the AWS profile more securely, then I’d suggest you read and apply the steps described in setting up AWS CLI with AWS Single Sign-On (SSO).

In order to configure the AWS CLI with your IAM user’s access and secret key credentials, you need to login to the AWS Console.

Go to IAM > Users, select your IAM user, and click on the Security credentials tab to create an access and secret key.

Then configure the AWS profile on the AWS CLI as follows:

➜ aws configure
AWS Access Key ID [None]: <insert_access_key>
AWS Secret Access Key [None]: <insert_secret_key>
Default region name [None]: <insert_aws_region>
Default output format [json]: json

Your was credentials are stored in ~/.aws/credentials and you can validate that your AWS profile is working by running the command:

➜ aws sts get-caller-identity
{
    "UserId": "AIDA5BRFSNF24CDMD7FNY",
    "Account": "012345678901",
    "Arn": "arn:aws:iam::012345678901:user/test-user"
}

2. Setting up the Python Environment

To be able to run the Python boto3 script, you will need to have Python installed on your machine.

Depending on if you’re running LinuxmacOS, or Windows the installation goes like this:

# macOS install method:
brew install python

# Windows install method:
wget https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe
msiexec.exe /i https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

# Linux (Ubuntu) install method:
sudo apt install python3 python3-pip

Once you have installed Python, you will need to install the Boto3 library.

You can install Boto3 using pip, the Python package manager, by running the following command in your terminal:

pip install boto3

3. Create the Python script that allows you to find the AWS accounts based on the OU name

Once you have our environment set up, you can create the Python script.

Copy the following code into a new file on the desired location and name it: find_accounts_by_ou_name.py.

#  https://github.com/dannysteenman/aws-toolbox
#
#  License: MIT
#
# This script returns a list of acounts that are part of an Organizational Unit (OU)

import boto3
import sys

# Check if at least one OU name is provided as command-line argument
if len(sys.argv) < 2:
    print(f"Usage: python {sys.argv[0]} <ou_name1> <ou_name2> ...")
    exit(1)

# Get the list of organizational unit names from the command-line arguments
ou_names = sys.argv[1:]

# Create an AWS Organizations client
organizations = boto3.client("organizations")

# Call the list_roots method to get a list of roots in the organization
response = organizations.list_roots()

# Get the ID of the root
root_id = response["Roots"][0]["Id"]

# Iterate through the list of OU names and get the ID of each OU
ou_ids = []
for ou_name in ou_names:
    # Call the list_organizational_units_for_parent method to get a list of organizational units for the root
    response = organizations.list_organizational_units_for_parent(ParentId=root_id)

    # Use a list comprehension to filter the results by name and get the ID of the first match
    ou_id = [
        ou["Id"] for ou in response["OrganizationalUnits"] if ou["Name"] == ou_name
    ][0]
    ou_ids.append(ou_id)

# Call the list_accounts method for each OU ID to get a list of accounts for each OU
accounts = []
for ou_id in ou_ids:
    response = organizations.list_accounts_for_parent(ParentId=ou_id)
    accounts.extend(response["Accounts"])

print(f"Found the following accounts for organizational units: {ou_names}\n")
for account in accounts:
    print(
        f'Account ID: {account["Id"]}, Account Alias/Name: {account.get("Alias", account["Name"])}'
    )

The script shown above offers a more developer-friendly way to locate AWS accounts based on OU names, overcoming the limitations imposed by AWS’s native approach.

First, it begins by checking if at least one OU name is provided as a command-line argument. If not, it prompts the user with the correct usage and exits.

It then proceeds to create an AWS Organizations client and retrieves the list of roots in the organization.

The script iterates through the provided OU names, and for each name, it queries the AWS Organizations API to get a list of organizational units for the root.

It filters the results by name and retrieves the ID of the first match, ultimately storing the OU IDs in a list.

Finally, the script calls the AWS Organizations API again, this time using the collected OU IDs to list the accounts associated with each OU.

The results are then displayed in a human-readable format, showing the account IDs and their corresponding account aliases or names.

4. Run the python script on your AWS management account

Before you run the script, you need to make sure to assume a role in the AWS management account. That is the account that is the owner of the AWS Organizations setup.

This is the only account that has permission to call the organizations API on AWS. If you want to run it on another AWS account within the AWS Organization, then I suggest you enable delegated administrator for AWS Organizations first.

Let’s proceed, to run the script, simply execute the following command in your terminal or command prompt:

 python find_accounts_by_ou_name.py <ou_name1> <ou_name2>

Replace <ou_name1> and <ou_name2> with the names of the Organizational Units, you want to find the AWS accounts for. You can provide as many OU names as you want.

➜ python organizations/find_accounts_by_ou_name.py Sandbox Application

Found the following accounts for organizational units: ['Sandbox', 'Application']

Account ID: 123456789012, Account Alias/Name: aws-sandbox-012
Account ID: 234567890123, Account Alias/Name: aws-sandbox-010
Account ID: 345678901234, Account Alias/Name: aws-sandbox-013
Account ID: 456789012345, Account Alias/Name: aws-sandbox-011
Account ID: 567890123456, Account Alias/Name: aws-dev-org-prd
Account ID: 678901234567, Account Alias/Name: aws-dev-org-tst

The script will output the AWS account IDs and their aliases/names for each Organizational Unit you provided as input.

Conclusion

By harnessing the power of Boto3 and the AWS Organizations API, the script in this blog post effectively bridges the gap left by AWS’s native functionality, allowing you to find and list AWS accounts based on their human-readable OU names rather than the less intuitive OU IDs.

Not only does this save time and effort, but it also enhances the overall user experience, making it easier for developers and engineers to manage the AWS Organization.



Danny Steenman

A Senior AWS Cloud Engineer with over 9 years of experience migrating workloads from on-premises to AWS Cloud.

I have helped companies of all sizes shape their cloud adoption strategies, optimizing operational efficiency, reducing costs, and improving organizational agility.

Connect with me today to discuss your cloud aspirations, and let’s work together to transform your business by leveraging the power of AWS Cloud.

I need help with..
stacked cubes
Improving or managing my CDK App.Maximize the potential of your AWS CDK app by leveraging the expertise of a seasoned CDK professional.
Reducing AWS Costs.We can start by doing a thorough assessment of your current AWS infrastructure, identifying areas with potential for cost reduction and efficiency improvement.
Verifying if my infrastructure is reliable and efficient.We’ve created a comprehensive AWS Operations Checklist that you can utilize to quickly verify if your AWS Resources are set up reliably and efficiently.