首页 > 解决方案 > Terraform - 云从列表中运行多个环境变量

问题描述

我正在尝试在我创建的云运行模块上设置多个环境变量。我从 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
   }
}

但我收到以下错误:

对“each.value”的引用已在其不可用的上下文中使用,例如当配置不再包含其“for_each”表达式中的值时。删除配置中对 each.value 的此引用以解决此错误。

编辑:完整代码示例

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
}

标签: terraformgoogle-cloud-run

解决方案


使用动态块时,不能使用each. 它应该是:

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

推荐阅读