You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform Dynamic块for_each未遍历全部元素问题求助

解决Terraform GuardDuty Filter动态块仅保留最后一个条件的问题

问题根源

你的本地变量test_filters中,finding_criteria是Map结构,且包含两个同名的criterion键。Terraform的Map不允许重复键,后定义的键会直接覆盖前一个,导致实际只有最后一个criterion被传入资源配置。

修正方案

1. 调整本地变量数据结构

将finding_criteria下的重复criterion键改为列表,确保所有条件都能被保留:

locals {
  test_filters = {
    Filter1 = {
      finding_criteria = [
        {
          field  = "region"
          equals = ["eu-west-1"]
        },
        {
          field  = "region1"
          equals = ["eu-west-2"]
        }
      ]
    }
  }
}

2. 修改资源的动态块逻辑

aws_guardduty_filter资源只需要一个finding_criteria块,内部可以包含多个criterion块。因此不需要动态生成finding_criteria,而是在该块内部动态生成criterion:

resource "aws_guardduty_filter" "test-filters" {
  for_each = local.test_filters
  name        = "test"
  action      = "ARCHIVE"
  detector_id = detector_test.detectorid
  rank        = 0

  finding_criteria {
    dynamic "criterion" {
      for_each = each.value.finding_criteria
      content {
        field  = criterion.value.field
        equals = criterion.value.equals
      }
    }
  }
}

验证效果

调整后执行terraform plan,会看到finding_criteria块内包含两个criterion条目,符合预期:

# aws_guardduty_filter.test-filters["Filter1"] will be created
  + resource "aws_guardduty_filter" "test-filters" {
      + action      = "ARCHIVE"
      + arn         = (known after apply)
      + detector_id = "xxxx"
      + id          = (known after apply)
      + name        = "test"
      + rank        = 0
      + tags_all    = (known after apply)

      + finding_criteria {
          + criterion {
              + equals     = [
                  + "eu-west-1",
                ]
              + field      = "region"
              + not_equals = []
            }
          + criterion {
              + equals     = [
                  + "eu-west-2",
                ]
              + field      = "region1"
              + not_equals = []
            }
        }
    }

Plan: 1 to add, 0 to change, 0 to destroy.

内容的提问来源于stack exchange,提问作者Thrupthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 13:28:32