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

Terraform报错:遍历非可迭代值及contains函数调用失败求助

问题分析与解决

核心问题

你遇到的两个错误根源分别是变量混淆和函数用法错误:

  1. 第一次报错(Iteration over non-iterable value)
    你模块内的var.pipeline_list是单个列表类型(对应var.pipelines中某个key的列表值,比如Infrastructure对应的那两个yml路径),但你错误地用了键值对遍历(for project, pipelines in var.pipeline_list),这种遍历方式只适用于map/object类型,所以Terraform报错无法迭代非可迭代值。

  2. 第二次报错(Call to function "contains" failed)
    contains函数的作用是判断集合(列表/元组/集合)是否包含某个元素,而不是判断字符串是否包含子串。你把字符串传给contains当第一个参数,不符合函数参数要求,因此报错。


正确实现代码

在你的模块中,var.pipeline_list是单个列表,直接遍历该列表,用strcontains(Terraform 0.13+支持)判断字符串是否包含"Deploy"子串,再用compact过滤掉null值即可:

locals {
  deploy_pipelines = compact([
    for pipeline in var.pipeline_list :
      strcontains(pipeline, "Deploy") ? pipeline : null
  ])
}

代码说明:

  • strcontains(pipeline, "Deploy"):检查字符串pipeline中是否包含子串"Deploy",返回布尔值。
  • 三元表达式:符合条件保留原字符串,不符合则返回null。
  • compact:自动移除列表中的所有null元素,得到干净的过滤结果。

兼容旧Terraform版本(<0.13)的替代方案

如果你的Terraform版本较低,用regex函数实现相同逻辑:

locals {
  deploy_pipelines = compact([
    for pipeline in var.pipeline_list :
      regex("Deploy", pipeline) != "" ? pipeline : null
  ])
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:29:58