Terraform - 云 运行 列表中的多个环境变量

Terraform - cloud run multiple environment variables from list

我正在尝试在我创建的云 运行 模块上设置多个环境变量。我从 Terraform 获取的示例是静态的。是否可以动态创建这些?

template {
    spec {
      containers {
        image = "us-docker.pkg.dev/cloudrun/container/hello"
        env {
          name = "SOURCE"
          value = "remote"
        }
        env {
          name = "TARGET"
          value = "home"
        }
      }
    }
  }

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_service#example-usage---cloud-run-service-multiple-environment-variables

我试过:

dynamic "env" {
   for_each = var.envs
   content {
     name  = each.key
     value = each.value
   }
}

但是我得到以下错误:

A reference to "each.value" has been used in a context in which it unavailable, such as when the configuration no longer contains the value in │ its "for_each" expression. Remove this reference to each.value in your configuration to work around this error.

编辑:完整代码示例

resource "google_cloud_run_service" "default" {
  name     = "cloudrun-srv"
  location = "us-central1"

  template {
    spec {
      containers {
        image = "us-docker.pkg.dev/cloudrun/container/hello"
        env {
          name = "SOURCE"
          value = "remote"
        }
        env {
          name = "TARGET"
          value = "home"
        }
      }
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }
  autogenerate_revision_name = true
}

当您使用动态块时,您不能使用each。应该是:

dynamic "env" {
   for_each = var.envs
   content {
     name  = env.key
     value = env.value
   }
}