Count and for_each doesn't go hand in hand

Need to attach multiple iam policy created using resource “aws_iam_policy” to Multiple Iam Roles using resource “aws_iam_role_policy_attachment” but not able to do it

variable "role_names" {
  description = "A list of one or more roles that the policy will be attached to"
  type        = list(string)
}

resource "aws_iam_policy" "policy_from_files" {
  for_each    = local.files
  name        = "${local.application_string_prefix}-${trimsuffix(each.value, ".json")}"
  description = var.description
  policy      = file("${path.module}/${var.policy_file_folder}/${each.value}")
  path        = var.path
  tags        = merge(var.app_tags, local.iac_tags)
}

Doesn’t work an count and for_each , The “count” and “for_each” meta-arguments are mutually-exclusive, only one should be used to be explicit about the number of resources to be created.

resource "aws_iam_role_policy_attachment" "policy_from_files_attachment" {
    count      = var.role_names == [] ? 0 : length(var.role_names)
    role       = element(var.role_names, count.index)
    for_each   = aws_iam_policy.policy_from_files
    policy_arn = each.value.arn
    depends_on = [aws_iam_policy.policy_from_files]
}

Hi @krobinsonjoe,

I’m not sure I fully understand what you are asking but I think you are intending to declare one instance of this aws_iam_role_policy_attachment for each distinct combination of aws_iam_policy.policy_from_files instances and var.role_names elements.

The usual way to do that is to use the setproduct function to calculate a new data structure with one element for each combination, and then use that as the basis for for_each. There’s an example of that in the setproduct documentation page.