Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

AWS Logo
Menu
Terraform: Active Accounts List

Terraform: Active Accounts List

Use a list of active accounts in an AWS organization to create Terraform resources.

Published Dec 19, 2024
Last Modified Dec 20, 2024
Recently, I had to create a new AWS IAM Identity Center Permission Set and assign it to all accounts in the organization. Since there were hundreds of accounts to work with in multiple Organizational Units (OU), checking each account one-by-one in the console wasn't very practical, so I tried to find other ways to do it.
There are several ways to achieve this, among which:
  1. Use AWSCLI or the SDK (e.g.: Python boto3) to assign the Permission Set to all accounts. Both of these methods allow commands to be run in parallel, reducing the time it takes to perform the task.
  2. Use CloudFormation to target all accounts simultaneously.
  3. Use Terraform to do something similar.
The problem with approaches (2) and (3) is that the Permission Set account assignment resources in both platforms only allows targeting accounts, not OUs and / or the whole organization, and approach (1) means that I needed to do this outside of our Infrastructure-as-Code (IaC) repositories. So, I decided to keep to Terraform, but iterate through the active accounts using Terraform loops. The keyword here is active, because targetting suspended accounts will return errors during the apply process. This means having a condition inside the loop to filter out non-active accounts.
Step 1: Get accounts data from the organization.
Step 2: Use loop(s) inside resource stanzas.
The line if account.status == "ACTIVE" ensures that the resource will only be provisioned for active accounts among all organization accounts. "SUSPENDED" accounts (pending deletion) will be skipped.
You can also list accounts from a specific OU instead of the entire organization by specifying its ID as the parent_id. If you need to be more surgical, you can even specify account IDs directly and forgo the data source declarations:

References: 

Comments