Looping through the objects created using for_each

Hi,
Am trying to create “aws_iam_policy_document” using for_each loop based on the property using list of string [env-prefix = [“dev”, “test”], After these objects are created i want to use these objects in “aws_iam_policy” for linking the policy with the policy document. Please find the below code. Am not able to iterate through the objectes created in “aws_iam_policy_document” and attached each policy to the policy document.

data "aws_iam_policy_document" "assume-crx-role-policy-doc" {
   for_each = { for x in var.cross-account-specs: "${x.external_role}-${x.env_prefix}" => x }
  statement {
    sid = "1"

    actions = [
      "sts:AssumRole",
    ]

    resources = [
      #"${var.cross-account-role-arns[count.index]}"  
      "${each.value.external_role}"
    ]
  }
}

resource "aws_iam_policy" "assume-crx-role-policy" {
    for_each = { for x in var.cross-account-specs: "${x.external_role}-${x.env_prefix}" => x }
    name = "${var.implementation-shortname}-assume-crx-policy-${each.value.env_prefix}"
    path = "/"
    description = "This policy will be used for assuming crx roles and accessing crx resources"
  # policy = data.aws_iam_policy_document.assume-crx-role-policy-doc[count.index].json
    policy = [ for p in data.aws_iam_policy_document.assume-crx-role-policy-doc[*]: p.json]

    tags = {
        dc-implementation-id = var.implementation-id
        dc-implementation-shortname = var.implementation-shortname
        dc-partner-id = var.partner-id
        dc-environment = var.environment
        dc-customer-id = var.customer-id
        map-migrated = var.map-migrated
  }
}

Following is the error am getting.

│ Error: Incorrect attribute value type
│
│   on 02 - iam-init-policies.tf line 23, in resource "aws_iam_policy" "assume-crx-role-policy":
│   23:     policy = [ for p in data.aws_iam_policy_document.assume-crx-role-policy-doc[*]: p.json]
│     ├────────────────
│     │ data.aws_iam_policy_document.assume-crx-role-policy-doc is object with 3 attributes
│
│ Inappropriate value for attribute "policy": string required.

Kindly assist.

Nearly correct, but count.index is for count, and you are using for_each - so you need to use each.key instead.

Hi Maxb,

That is commented value which you have seen, actually value is below that, could you please check and suggest, I want to iterate through objects created in previous resources, And the object is json file which is created in “aws_iam_policy_document”

So, un-comment it. It’s closer to correct than the other version.