gpt4 book ai didi

terraform - 如何同时循环locals和list生成资源

转载 作者:行者123 更新时间:2023-12-02 19:08:07 26 4
gpt4 key购买 nike

我有以下 tf 文件:

locals {
schemas = {
"ODS" = {
usage_roles = ["TRANSFORMER"]
}
"EXT" = {
usage_roles = []
}
"INT" = {
usage_roles = ["REPORTER"]
}
"DW" = {
usage_roles = ["LOADER"]
}
}
}

resource "snowflake_schema" "schema" {
for_each = local.schemas
name = each.key
database = ???????
usage_roles = each.value.usage_roles
}

我想按原样维护局部变量(每个模式的不同 usage_roles 并在此处进行硬编码),同时将多个值作为每个模式的数据库。在伪代码中它将是:

for database in ['db_1', 'db_2', 'db_3']:
resource "snowflake_schema" "schema" {
for_each = local.schemas
name = each.key
database = database
usage_roles = each.value.usage_roles
}

这样我们在三个不同的数据库中就有了相同的schema资源。我读过一些文章让我相信可以创建这个循环但预先分配所有值,这意味着我必须将 usage_roles 放在列表或其他东西中而不是在本地硬编码,我认为这是可读性较差。例如: Terraform - how to use for_each loop on a list of objects to create resources

甚至有可能实现我的要求吗?如果是这样,如何?非常感谢您提前

最佳答案

for_each 的主要要求是您提供的映射必须为您要创建的每个资源实例提供一个元素。在你的情况下,我认为这意味着你需要一个 map ,每个数据库和模式的组合都有一个元素。

在两个集合中查找每个值组合的操作正式称为 cartesian product , Terraform 有 the setproduct function执行该操作。在您的情况下,要应用它的两组是数据库名称集和模式映射中的键集,如下所示:

locals {
databases = toset(["db_1", "db_2", "db_3"])

database_schemas = [
for pair in setproduct(local.databases, keys(local.schemas)) : {
database_name = pair[0]
schema_name = pair[1]
usage_roles = local.schemas[pair[1]].usage_roles
}
]
}

local.database_schemas 值将包含每个组合的对象,如下所示:

[
{
database_name = "db_1"
schema_name = "ODS"
usage_roles = ["TRANSFORMER"]
},
{
database_name = "db_1"
schema_name = "EXT"
usage_roles = []
},
# ...
{
database_name = "db_2"
schema_name = "ODS"
usage_roles = ["TRANSFORMER"]
},
{
database_name = "db_2"
schema_name = "EXT"
usage_roles = []
},
# ...
{
database_name = "db_3"
schema_name = "ODS"
usage_roles = ["TRANSFORMER"]
},
{
database_name = "db_3"
schema_name = "EXT"
usage_roles = []
},
# ...
]

这满足了您要创建的每个实例都有一个元素的要求,但我们仍然需要将其转换为每个元素具有唯一键的 map ,以便为每个实例为 Terraform 提供唯一的跟踪键,因此我们可以做一个for_each 参数中的更多 for 投影:

resource "snowflake_schema" "schema" {
for_each = {
for s in local.database_schemas :
"${s.database_name}:${s.schema_name}" => s
}

name = each.value.schema_name
database = each.value.database_name
usage_roles = each.value.usage_roles
}

Terraform 将使用如下地址跟踪这些实例:

  • snowflake_schema.schema["db_1:ODS"]
  • snowflake_schema.schema["db_1:EXT"]
  • ...
  • snowflake_schema.schema["db_2:ODS"]
  • snowflake_schema.schema["db_2:EXT"]
  • ...
  • snowflake_schema.schema["db_3:ODS"]
  • snowflake_schema.schema["db_3:EXT"]
  • ...

关于terraform - 如何同时循环locals和list生成资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64756607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com