避免 terraform 变量列表中的重复(Google Cloud Run)

问题描述 投票:0回答:1

我有一个想要供 Google Cloud Run 实例使用的环境变量列表(1 个服务,4 个作业)

环境变量在这些作业之间大量共享,如果我需要添加/更改/删除其中任何一个,我需要执行 5 次,显然这为错误产生了机会,而且我经常重复自己。

我想到有一个包含所有这些值的变量,然后将它们解压到 terraform 声明的

containers
部分。

resource "google_cloud_run_v2_job" "example_cloud_run_job" {
  # project, location, name, dependency info in here
  template {
    # template info such as parallelism and task count here
    template {
      # more info in here
      containers {
        # image, networking info, resources in here, but also a lot of environment variables!
        env {
          name  = "foo"
          value = var.bar
        }
        env {
          name  = "baz"
          value = var.qux
        }
        env {
          name  = "quux"
          value = var.corge
        }
        env {
          name  = "grault"
          value = var.garply
        }
      }
    }
  }
}

我希望我可以做一些事情来将这些变量解压到

containers
对象中,类似于我们在 JavaScript/Typescript 中使用
...
运算符或 Python 中的
*
运算符来完成此操作。我在 Terraform 的文档中找不到这个,我确信我不是第一个遇到这个问题的人!

我一直在阅读文档并在代码中进行一些尝试,但没有找到可靠的方法。

terraform google-cloud-run terraform-provider-gcp
1个回答
1
投票

您可以做的是将

for_each
元参数与
dynamic
结合使用。您还需要创建一个用于迭代的变量:

variable "env_vars" {
  type        = map(string)
  description = "Map of environment variables."

  default = {
    foo    = "some value"
    baz    = "some value"
    quux   = "some value"
    grault = "some value"
  }
}

resource "google_cloud_run_v2_job" "example_cloud_run_job" {
  # project, location, name, dependency info in here
  template {
    # template info such as parallelism and task count here
    template {
      # more info in here
      containers {
        dynamic "env" {
          for_each = var.env_vars
          content {
            name  = env.key
            value = env.value
          }
        }
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.