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

Terraform嵌套模块条件输出变量报错:不存在s3_list属性

问题解决:Terraform模块间变量引用报错

错误根源

  1. 模块未输出变量:你的storage_bucket模块没有将输入的s3_list变量定义为输出,主模块自然无法通过module.bucket.s3_list访问该变量。
  2. 引用逻辑错误:s3_list是map类型(键为bucket_1/bucket_2等),不是列表,不能用.0这种列表索引方式访问;同时原代码的条件判断和lookup函数用法完全不符合需求逻辑。

修复步骤

1. 为storage_bucket模块添加输出变量

在../modules/storage_bucket目录下创建outputs.tf文件,将输入的s3_list变量暴露为模块输出:

output "s3_list" {
  type        = map(object({
    name               = string
    bucket_policy_only = bool
    role_entity        = list(string)
    lifecycle_rule     = list(any)
  }))
  value       = var.s3_list
  description = "传入的存储桶配置集合"
}

2. 修正functions模块的引用代码

根据需求,直接从s3_list的map结构中按key取值,修改后的调用代码如下:

module "bucket_func" {
  source        = "../modules/functions"
  func_1_name   = module.bucket.s3_list.bucket_1.name != "" ? module.bucket.s3_list.bucket_1.name : null
  func_2_name   = module.bucket.s3_list.bucket_2.name != "" ? module.bucket.s3_list.bucket_2.name : null
  func_5_name   = module.bucket.s3_list.bucket_5.name != "" ? module.bucket.s3_list.bucket_5.name : null
}

额外说明

如果需要引用实际创建的存储桶属性(比如桶的自动生成URL),而非输入的配置变量,需要修改storage_bucket模块的输出为资源属性:

output "created_buckets" {
  type        = map(object({
    name = string
    url  = string
  }))
  value       = {
    for k, v in google_storage_bucket.storage_bucket : k => {
      name = v.name
      url  = v.url
    }
  }
  description =  "实际创建完成的存储桶信息(仅包含bucket_policy_only=true的桶)"
}

此时functions模块需改为引用module.bucket.created_buckets.bucket_x.name。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 11:24:16