'I want to iterate over iam_policy module, creating multiple, and attach each one to their iam_assumable_role counterpart. Is there a work around?

Ok, I hope there is a way to do this. So I I have a list, lets say var.env. And I want to iterate over that var.env to make multiple policies and attach those to their counterpart assumable role. I hope that make sense.

What this would look like is.

# list
variable "env" {
  type = list(strings)
  default = ['dev', 'stage', 'prod']
}

# creating the policy documents data
data "aws_iam_policy_document" "policy_document" {
  for_each = var.env

  statement {
    actions = [
      "s3:*"
    ]
    effect = "Allow"
    resources = ["arn:...:mybucket_${each.key}"]
  }
}

# attaching the policy document data to a policy
module "bucket_policy" {
  source   = "terraform-aws-modules/iam/aws//modules/iam-policy"
  version  = "4.10.0"

  for_each = var.env

  name        = "example_${each.key}_bucket_policy"
  path        = "/"
  description = "${each.key} Policy document"

  policy = data.aws_iam_policy_document.policy_document[each.key].json
}

# creating the assumable roles 
module "assumable_role" {
  source   = "terraform-aws-modules/iam/aws//modules/iam-assumable-role"
  version  = "4.10.0"

  for_each = var.env

  create_role = true

  role_name         = "example_${each.key}_bucket_role"
  role_requires_mfa = false

  trusted_role_services = [
    s3.amazonaws.com"
  ]

  # now this DOESN"T WORK but something like this... 
  custom_role_policy_arns = [
    module.bucket_policy.arn[each.key]
  ]
}

I truly appreciate the advice and everything.

Thank you beforehand.



Solution 1:[1]

The correct way to referrer to the arn is as follows. Instead of

 module.bucket_policy.arn[each.key]

it should be

 module.bucket_policy[each.key].arn

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin