We have a following scenario in our AWS account,
.
└── Root account = r-abc
└── Cloud OU = ou-1
├── Dev OU = ou-2
│ ├── Acc1
│ └── Acc2
├── Stage OU = ou-3
│ ├── AccA
│ └── AccB
└── Prod OU = ou-4
├── AccX
└── AccY
Could you please assist with the necessary lines I need to generate the output of accounts in ou-4
via Terraform? We need to list accounts using the OU ID - ou-4.
Tried
data "aws_organizations_organization" "org" {}
data "aws_organizations_organizational_units" "ou" {
parent_id = data.aws_organizations_organization.org.roots[0].id
}
data "aws_organizations_organizational_unit_descendant_accounts" "org" {
for_each = { for ou in data.aws_organizations_organizational_units.ou.children : ou.name => ou.id }
parent_id = each.value
}
output "accounts_nested_by_ou" {
description = "nested map of all accounts (except master) by child OU if no nested OUs in org"
value = { for ou_name, ou_attributes in data.aws_organizations_organizational_unit_descendant_accounts.org: ou_name =>
{
for accounts in ou_attributes.accounts: accounts.name => accounts.id
}
}
}
Output received
Changes to Outputs:
+ accounts_nested_by_ou = {
+ Cloud OU = {
+ Acc1 = "111111111111"
+ Acc2 = "222222222222"
+ AccA = "AAAAAAAAAAAA"
+ AccB = "BBBBBBBBBBBB"
+ AccX = "XXXXXXXXXXXX"
+ AccY = "YYYYYYYYYYYY"
}
}
You can apply this plan to save these new output values to the Terraform state, without changing any real
infrastructure.
Expected Output
Changes to Outputs:
+ accounts_nested_by_ou = {
+ Prod OU = {
+ AccX = "XXXXXXXXXXXX"
+ AccY = "YYYYYYYYYYYY"
}
}
You can apply this plan to save these new output values to the Terraform state, without changing any real
infrastructure.
Based on the code you have provided in the question and you have tried, if the OU name is really Prod
, then this should work:
output "accounts_nested_by_ou" {
description = "nested map of all accounts (except master) by child OU if no nested OUs in org"
value = { for ou_name, ou_attributes in data.aws_organizations_organizational_unit_descendant_accounts.org : ou_name => {
for accounts in ou_attributes.accounts : accounts.name => accounts.id
} if ou_name == "Prod"
}
}
In my organization, this shows the following output:
+ accounts_nested_by_ou = {
+ Prod = {
+ account-name = "012345678910"
}
}
In general, this should work whateve the real name of the Prod OU is, just swap it in the if
condition with the value you want.