使用for_each填写列表参数

时间:2020-10-26 18:40:27

标签: terraform hcl

我正在尝试将条目添加到labels resource上的metadatagoogle_monitoring_metric_descriptor子块中。我很难让for_each遍历每个度量指标描述符的结构图,以及labelsmetadata的内部集合。它似乎没有接受块中的内部for_each,并且尝试使用=进行分配似乎也不起作用。


locals {
  metrics = {
    gsuite_user_count = {
      name = "projects/my-gcp-project-123/metricDescriptors/custom.googleapis.com/gsuite_user_count",
      labels = [
        {
          key = "gsuite_domain"
        },
        {
          key         = "opencensus_task",
          description = "Opencensus task identifier"
        }
      ],
      metricKind  = "GAUGE",
      valueType   = "INT64",
      unit        = "1",
      description = "Number of users in GSuite Directory.",
      displayName = "custom.googleapis.com/gsuite_user_count",
      type        = "custom.googleapis.com/gsuite_user_count"
    }
  }
}

resource "google_monitoring_metric_descriptor" "basic" {
  provider     = google-beta
  for_each     = local.metrics
  description  = lookup(each.value, "description")
  display_name = each.value.displayName

  # How do I do this?
  labels = [for label in each.value.labels : {
    key   = label.key
    value = label.value
  }]

  //  launch_stage = each.value.launchStage
  //  metadata     = each.value.metadata
  metric_kind = each.value.metricKind
  type        = each.value.type
  unit        = each.value.unit
  value_type  = each.value.valueType
  project     = var.project_id
}

这会在terraform apply上显示此错误:

Error: Unsupported argument

  on /Users/jaycarlton/repos/workbench/ops/terraform/modules/workbench/modules/monitoring/modules/metrics/main.tf line 32, in resource "google_monitoring_metric_descriptor" "basic":
  32:   labels = [for label in each.value.labels : {

An argument named "labels" is not expected here. Did you mean to define a
block of type "labels"?

1 个答案:

答案 0 :(得分:2)

可以使用dynamic blocks迭代设置标签。可能是沿着这些路线:

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