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

Terraform嵌套循环用条件表达式报错:缺失项分隔符

问题

我编写了如下Terraform表达式:

flatten(
        [
          for region in local.customers: [
            for customer in region: [
              customer.customer_code if length(regexall("foo", customer.name)) == 0 && length(regexall("bar", customer.name)) == 0
            ]
          ]
        ]
      )

执行时出现错误:

The Terraform configuration must be valid before initialization so that
Terraform can determine which modules and providers need to be installed.
╷
│ Error: Missing item separator
│ 
│ On alerts.tf line 34: Expected a comma to mark the beginning of the next
│ item.

我无法找到正确的语法。而如下单循环带条件的表达式可正常运行:

[for c in local.customers["a_region"] : c.name if length(regexall("foo", c.name)) == 0 && length(regexall("bar", c.name)) == 0]

这说明条件部分无问题,但将逻辑应用到嵌套循环并结合flatten后就报错了,请问问题出在哪里?

原因与修复方案

问题出在最内层的列表推导式语法错误。Terraform的列表推导式要求if条件必须放在循环主体的末尾,而不是跟在返回值后面,同时你在最内层额外套了一层不必要的[],这导致Terraform无法解析正确的语法结构。

正确的写法需要去掉最内层的多余列表包裹,把条件移到循环的末尾:

flatten(
  [
    for region in local.customers : [
      for customer in region : customer.customer_code
      if length(regexall("foo", customer.name)) == 0 && length(regexall("bar", customer.name)) == 0
    ]
  ]
)

说明:

  • 原写法中[customer.customer_code if ...]不符合Terraform列表推导式的规范,正确结构是[for <item> in <collection> : <返回值> if <条件>]。
  • 外层循环已经在生成嵌套列表,flatten会自动将嵌套结构展开为一维数组,不需要给单个返回值额外套列表。

如果想简化条件判断,可以用正则匹配更简洁地实现“名称不包含foo或bar”的逻辑:

flatten(
  [
    for region in local.customers : [
      for customer in region : customer.customer_code
      if can(regex("^(?!.*(foo|bar)).*$", customer.name))
    ]
  ]
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 02:07:01