gpt4 book ai didi

azure - 将 Terraform Locals 用于列表对象 {type = list(object({}))}

转载 作者:行者123 更新时间:2023-12-02 23:22:11 26 4
gpt4 key购买 nike

请问如何使用局部变量简化此配置,代码按原样工作正常,但每次手动传递变量都会变得复杂。

变量:

variable "vm_all" {
type = list(object({}))
default = [
{
name = "vm1"
rg = "rg1"
sn = "sn1"
sn_prefix = ["10.0.1.0/24"]
},
{
name = "vm2"
rg = "rg2"
sn = "sn2"
sn_prefix = ["10.0.2.0/24"]
},
{
name = "vm3"
rg = "rg3"
sn = "sn3"
sn_prefix = ["10.0.3.0/24"]
}
]
}

使用局部变量进行当前迭代:(需要手动映射变量,如上所示)

resource "example_resource" "resource1" {
for_each = {for vm_all in var.vm_all: vm_all.name => vm_all }
name = each.value.name
rg = each.value.rg
sn = each.value.sn
sn_prefix = each.value.sn_prefix
}

所需的传递变量的方法:

 variable "name" {
default = [
"vm1",
"vm2",
"vm3"
]
}

variable "rg_names" {
default = [
"rg1",
"rg2",
"rg3"
]
}

variable "subnets" {
default = [
"sn1",
"sn2",
"sn3"
]
}

variable "subnet_prefixes" {
default = [
"sn_prefix1",
"sn_prefix2",
"sn_prefix3"
]
}

问题:如何以更有效的方式使用局部变量以允许按上面显示的列表传递变量并避免手动映射?

最佳答案

您可以按如下方式组合它们:

locals {
vm_all = {for idx, name in var.name:
name => {
"name" = name
rg = var.rg_names[idx]
sn = var.subnets[idx]
sn_prefix = [var.subnet_prefixes[idx]]
}
}
}

然后

resource "example_resource" "resource1" {
for_each = local.vm_all
name = each.value.name
rg = each.value.rg
sn = each.value.sn
sn_prefix = each.value.sn_prefix
}

关于azure - 将 Terraform Locals 用于列表对象 {type = list(object({}))},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73832153/

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