Iam policy, multiple resources, and for_each

I’m using AWS.
I have one parent account.
I have many children accounts.

I have a policy in the parent, which allows IAM users to assume children accounts:

data "aws_iam_policy_document" "assume" {
  statement {
    sid    = "AssumeIntoChildren"
    effect = "Allow"

    actions = [
      "sts:AssumeRole"
    ]

    resources = [
      "arn:aws:iam::ACCOUNT-ID-WITHOUT-HYPHENS:role/assume-into-me"
    ]
  }
}

I can get a list of all accounts:

data "aws_organizations_organization" "all_accounts" {}

Is it possible to use for_each to loop over data.aws_organizations_organization.all_accounts.accounts[*].id when defining the resources in my iam policy?

If not, I’m stuck modifying this policy every time I add an account.

Hi @throwaway8787,

I’m not familiar with AWS Organizations specifically so my answer here is focused only on the relevant Terraform language features, but based on what you’ve said here I think you should be able to write something like this:

data "aws_iam_policy_document" "assume" {
  statement {
    sid    = "AssumeIntoChildren"
    effect = "Allow"

    actions = [
      "sts:AssumeRole"
    ]

    resources = [
      for id in data.aws_organizations_organization.all_accounts.accounts[*].id :
      "arn:aws:iam::${id}:role/assume-into-me"
    ]
  }
}

Assuming that the id attribute of the objects in the accounts attribute are suitable ids, the above should produce a suitable ARN for each of the returned accounts.