Data aws_iam_policy_document and for_each showing changes when count changes but not policy content

Hi All

AWS v5.25.0
Terraform v1.5.7

variable "queues" {
    type = list(object({
        id  = string,
    }))

    default = [
        { id = "1" },
    ]
}

resource "aws_sqs_queue" "queues" {
    for_each = { for queue in var.queues: "${queue.id}.fifo" => queue }

    name = "queue-${each.value.id}.fifo"
    fifo_queue = true
}

resource "aws_sqs_queue_policy" "queue" {
    for_each = aws_sqs_queue.queues

    queue_url = each.value.id
    policy = data.aws_iam_policy_document.queue-policy[each.key].json
}

data "aws_iam_policy_document" "queue-policy" {
    for_each = aws_sqs_queue.queues

    policy_id = each.value.name

    statement {
        sid = "__owner_statement"
        effect = "Allow"

        resources = [ each.value.arn ]

        actions = [
            "SQS:*",
        ]

        principals {
            identifiers = [ var.aws-account-id ]
            type        = "AWS"
        }
    }
}

When adding one more element to the “queues” (with id 2) variable terraform plan shows adding new changes related to the new queue (expected) BUT also changes to the current queue with id 1:

  # aws_sqs_queue_policy.queue["1"] will be updated in-place
  ~ resource "aws_sqs_queue_policy" "queue" {
        id        = "<hidden>"
      ~ policy    = jsonencode(
            {
              - Id        = "queue-1.fifo"
              - Statement = [
                  - {
                      - Action    = "SQS:*"
                      - Effect    = "Allow"
                      - Principal = {
                          - AWS = "<hidden>"
                        }
                      - Resource  = "<hidden>"
                      - Sid       = "__owner_statement"
                    }
                ]
              - Version   = "2012-10-17"
            }
        ) -> (known after apply)
        # (1 unchanged attribute hidden)

Hi @amberovsky,

Something strange seems to be going on here, because your configuration seems to be constructing instance keys shaped like "1.fifo" and then using those same instances keys for the other resources using the chaining pattern, but the resource instance shown in your plan output has the instance "1", which seems like it should be impossible with this configuration.

Is there something more in your real configuration that you haven’t shared? :thinking:

Hi @apparentlymart ,

I don’t think so, because the issue disappears if I do HEREDOC policy in the aws_sqs_queue_policy directly, instead of using data.aws_iam_policy_document

Seems like the problem related to the IAM policy document / json conversion?

EDIT: sorry, I re-read your response, it must be my typo related to editing the output as there were a lot of sensitive data. I will check again to make sure it is indeed my type