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

Terraform:如何在单个资源内遍历嵌套集合生成dynamic rule块?

解决方案

要在单个pagerduty_event_orchestration_router资源中遍历var.test.nestedone和var.test.nestedtwo生成规则块,需要先将嵌套集合扁平化并合并,同时修正actions块的遍历逻辑,以下是可行的代码:

resource "pagerduty_event_orchestration_router" "test" {
  dynamic "rule" {
    # 扁平化并合并所有nestedone和nestedtwo中的规则元素
    for_each = flatten([
      for item in var.test : [
        for rule_one in item.nestedone : rule_one,
        for rule_two in item.nestedtwo : rule_two
      ]
    ])

    content {
      label = rule.value.label

      dynamic "condition" {
        for_each = rule.value.conditions
        content {
          expression = condition.value.expression
        }
      }

      # 将单个actions对象转为单元素列表,适配dynamic块的遍历要求
      dynamic "actions" {
        for_each = [rule.value.actions]
        content {
          route_to = actions.value.route_to
        }
      }
    }
  }
}

关键说明:

  1. 合并扁平化规则集合:
    原写法var.test[*].nestedone会生成一个包含多个集合的列表,无法直接用于for_each。通过嵌套for表达式,先遍历var.test中的每个顶层对象,再分别提取nestedone和nestedtwo内的所有规则元素,最后用flatten函数将嵌套列表转为扁平结构,得到所有规则的集合。

  2. 修正actions块遍历:
    变量中actions是单个object类型而非集合,不能直接作为for_each的参数。将其包裹在单元素列表[rule.value.actions]中,即可让dynamic块生成对应的actions配置块,并正确引用route_to字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:52:32