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

Terraform:从现有列表提取名称生成新列表的实现方法

不用null resource实现Terraform列表名称提取与拼接

当然可以!完全不需要借助null resource,Terraform的内置函数组合就能轻松搞定这个需求。咱们一步步来分解实现过程:

核心思路

先从每个分号分隔的字符串里提取名称部分,去除重复的名称,最后把它们拼接成逗号分隔的字符串。

具体实现代码

首先,假设你的items是定义在变量里的:

variable "items" {
  type        = list(string)
  description = "List of items with name, ports, and tags"
  default = [
    "name1; 60014; 443; Some text",
    "name1; 60012; 443; Some text",
    "name2; 60015; 80; Another text"
  ]
}

然后用下面的表达式就能得到你想要的结果:

output "unique_names" {
  value = join(",", distinct([for item in var.items : trimspace(split(";", item)[0])]))
}

函数拆解说明

  • split(";", item):把每个字符串按分号拆分成列表,比如第一个item会拆成["name1", " 60014", " 443", " Some text"]
  • trimspace(...):去掉拆分后名称部分的前后空格(避免字符串里的空格干扰最终结果)
  • [for item in var.items : ...]:遍历所有items,生成包含所有名称的临时列表
  • distinct(...):去除列表里重复的名称,得到唯一名称的列表
  • join(",", ...):把去重后的名称列表用逗号拼接成单个字符串

验证结果

对于你给出的示例items:

[
  "name1; 60014; 443; Some text",
  "name1; 60012; 443; Some text"
]

运行后输出的结果会是:"name1"

如果items里包含不同的名称,比如加入"name2; 60015; 80; Another text",结果就会是:"name1,name2"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:28:26