我已经创建了这个 terraform 变量。
variable "test" {
default = {
map1 = {
secrets = {
"user" = "user"
"pass" = "123456"
}
config = {
"setting1" = "123|456|789"
"setting2" = "123|456|789"
"setting3" = "123|456|789"
"setting4" = "123|456|789"
"setting100" = "123|456|789"
}
}
map2 = {
secrets = {
"user" = "user2"
"pass" = "123456"
}
config = {
"setting1" = "100500|456|789"
"setting2" = "123|100500|789"
"setting3" = "123|456|100500"
"setting4" = "123|100500|789"
"setting100" = "100500|456|789"
}
}
mapN = {
secrets = {
"user" = "userN"
"pass" = "123456"
}
config = {
"setting1" = "100500|456|789"
"setting2" = "123|100500|789"
"setting3" = "123|456|100500"
"setting4" = "123|100500|789"
"settingN" = "100500|456|789"
}
}
}
}
在这个变量中可能有大量的地图,例如,map1, map2, mapN
此外,还可能有许多具有不同名称的“设置”,例如setting1, setting2, dasdasd_23123, asdqw22_qq
,但值总是有三个元素"123|456|789"
。
我尝试将值传递给模块,例如:
module "test" {
source = "./test"
for_each = var.test
map_name = each.key
name1 = element(split("|", each.value.config), 0)
name2 = element(split("|", each.value.config), 2)
name3 = element(split("|", each.value.config), 1)
}
可以使用for_each
吗for_each
?有人有这样的经历吗?有人可以分享例子吗?谢谢!
答案1
variable "test" {
default = {
map1 = {
secrets = {
"user" = "user"
"pass" = "123456"
}
config = {
"setting1" = "123|456|789"
"setting2" = "123|456|789"
"setting3" = "123|456|789"
"setting4" = "123|456|789"
"setting100" = "123|456|789"
}
}
map2 = {
secrets = {
"user" = "user2"
"pass" = "123456"
}
config = {
"setting1" = "100500|456|789"
"setting2" = "123|100500|789"
"setting3" = "123|456|100500"
"setting4" = "123|100500|789"
"setting100" = "100500|456|789"
}
}
mapN = {
secrets = {
"user" = "userN"
"pass" = "123456"
}
config = {
"setting1" = "100500|456|789"
"setting2" = "123|100500|789"
"setting3" = "123|456|100500"
"setting4" = "123|100500|789"
"settingN" = "100500|456|789"
}
}
}
}
variable "flattened_test" {
default = [
for map_name, map_data in var.test :
{
map_name = map_name
secrets = map_data.secrets
config = {
for setting_name, setting_value in map_data.config :
"${setting_name}_value" => setting_value
}
}
]
}
module "test" {
source = "./test"
for_each = { for item in var.flattened_test : item.map_name => item }
map_name = each.key
name1 = element(split("|", each.value.config.setting1_value), 0)
name2 = element(split("|", each.value.config.setting1_value), 2)
name3 = element(split("|", each.value.config.setting1_value), 1)
}
在 locals 块中,我们创建一个新的局部变量 top_level_map_names,其中包含所有顶级映射名称的列表(map1、map2、mapN)。
然后,在模块块中,我们使用嵌套的 for_each 循环:
外循环迭代顶级映射名称 (local.top_level_map_names)。内循环迭代每个顶级映射中的嵌套映射 (secrets 和 config)。