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

Terraform中contains函数筛选列表异常,请求排查代码问题

修正Terraform字符串筛选的错误

你的代码问题出在contains函数的用法逻辑错误:
原代码中contains(["app"], app_id)是判断app_id是否是列表["app"]中的元素(即严格等于"app"),但你的目标元素是"app-1"、"app-2"这类带后缀的字符串,自然无法匹配,所以返回空列表。

根据你的需求,有两种修正方式:

方式一:使用strcontains检查字符串是否包含指定子串

适合需要匹配任意位置包含"app"的场景:

variable "tiers" {
  type    = list(string)
  default = ["app-1", "app-2", "db-1", "db-2"]
}

output "iterate-apps" {
  value = [
    for app_id in var.tiers : app_id
    if strcontains(app_id, "app")    
  ]
}

方式二:使用startswith匹配前缀(更精准)

因为你的目标字符串都是以"app-"开头,用这个方法可以避免误匹配其他包含"app"的字符串(比如"xxxapp-3"):

variable "tiers" {
  type    = list(string)
  default = ["app-1", "app-2", "db-1", "db-2"]
}

output "iterate-apps" {
  value = [
    for app_id in var.tiers : app_id
    if startswith(app_id, "app")    
  ]
}

两种方式都能得到你期望的输出:

iterate-apps = [
  "app-1",
  "app-2",
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:32:14