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

Terraform GCP中创建嵌套map(object)日志指标模板报错求助

解决Terraform GCP google_logging_metric嵌套配置错误

问题场景

在Terraform中配置GCP的google_logging_metric资源时,尝试通过tfvars文件传递嵌套的多对象值批量创建指标,执行时出现参数不支持的错误。

报错信息

╷
│ Error: Unsupported argument
│
│ on main.tf line 441, in resource "google_logging_metric" "logging_metric":
│ 441: labels = each.value.labels
│
│ An argument named "labels" is not expected here. Did you mean to define a block of type "labels"?

修正步骤

1. 修正变量类型定义(variables.tf)

原变量中labels的类型定义为map(string),无法匹配tfvars里嵌套的对象结构,需修改为嵌套的map(object):

variable "custom_logging_metrics" {
  description = "Map of custom logging metrics with labels and extractors"
  type = map(object({
    name             = string
    filter           = string
    metric_kind      = string
    value_type       = string
    label_extractors = map(string)
    labels = map(object({
      value_type  = string
      description = string
    }))
  }))
}

2. 修正资源配置中的labels块生成方式(main.tf)

google_logging_metric的metric_descriptor内的labels是Terraform嵌套块,不能直接用参数赋值,需通过dynamic块遍历变量中的labels生成对应子块:

resource "google_logging_metric" "logging_metric" {
  for_each = var.custom_logging_metrics

  name   = each.value.name
  filter = each.value.filter

  metric_descriptor {
    metric_kind = each.value.metric_kind
    value_type  = each.value.value_type

    dynamic "labels" {
      for_each = each.value.labels
      content {
        key         = labels.key
        value_type  = labels.value.value_type
        description = labels.value.description
      }
    }
  }

  label_extractors = each.value.label_extractors
}

核心原因

  • metric_descriptor下的labels是嵌套块结构,而非普通属性参数,必须通过dynamic块动态生成每个label的子块。
  • 变量类型定义需与tfvars中的实际数据结构匹配,否则会导致类型不兼容或解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:55:07