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

在Terraform中遍历对象列表并更新值(Terragrunt传参场景)

实现方法

你可以通过两种方式实现给列表内每个map的name字段添加前缀的需求,以下是具体方案:

方案一:在Terragrunt中处理变量(推荐)

直接在terragrunt.hcl里通过HCL的for表达式遍历push_subscriptions列表,对每个元素的name字段追加前缀,同时保留其他原有属性:

修改后的terragrunt.hcl代码:

include "product_vars" {
  path = find_in_parent_folders("_terragrunt.hcl")
}

inputs = {
  push_subscriptions = [
    for sub in [
      {
        name                       = "push-sub-1"                    
        ack_deadline_seconds       = 20                            
        push_endpoint              = "https://example.com"        
      },
      {
        name                       = "push-sub-2"                    
        ack_deadline_seconds       = 20                            
        push_endpoint              = "https://example.com"        
      }
    ] : merge(sub, {
      name = "pbsb-push-${var.product_environment_code}-${sub.name}"
    })
  ]
}
  • 用for循环遍历原始的订阅列表
  • 通过merge函数将原有属性和修改后的name字段合并,确保其他属性(如ack_deadline_seconds、push_endpoint)保持不变
  • ${var.product_environment_code}会引用从父级_terragrunt.hcl继承的环境变量值

方案二:在Terraform的main.tf中处理

如果希望在模块调用时统一处理变量,修改main.tf中的模块参数:

修改后的main.tf代码:

module "pubsub" {
  push_subscriptions = [
    for idx, sub in var.push_subscriptions : merge(sub, {
      name = "pbsb-push-${var.product_environment_code}-${sub.name}"
    })
  ]
}
  • 同样使用for表达式遍历var.push_subscriptions列表
  • 对每个元素的name字段添加指定前缀,通过merge保留其他属性
  • 注意需要确保var.product_environment_code在当前Terraform模块中已定义或通过变量传入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 23:27:28