使用Terraform v0.12.6 中的for_each表达式动态生成 vnet 子网 (Azure) 的内联块。我定义了列表变量“子网”,有两个子网“sub1”和“sub2”,如下所示
variable "subnets" {
default = [
{
name = "sub1"
prefix = "1.1.1.1/32"
},
{
name = "sub2"
prefix = "2.2.2.2/32"
},
]
}
Run Code Online (Sandbox Code Playgroud)
然后迭代“azurerm_virtual_network”块内的列表变量以创建子网的动态块
dynamic "subnet" {
for_each = [for s in var.subnets : {
name = s.name
prefix = s.prefix
}]
content {
name = subnet.name
address_prefix = subnet.prefix
}
}
}
Run Code Online (Sandbox Code Playgroud)
获取 ie 第一个是 错误:不支持的属性
在 main.tf 第 42 行,在资源“azurerm_virtual_network”“vnet”中:42:name = subnet.name
该对象没有名为“name”的属性。
为dynamic块创建的迭代器对象有两个属性:
key: 当前元素的映射键或列表索引value: 当前元素的值在这种情况下,用于重复的集合是一个对象列表,因此subnet.key整数索引 0, 1, ...subnet.value将是与该索引关联的对象。
要获得您正在寻找的结果,您需要改为访问对象属性subnet.value:
dynamic "subnet" {
for_each = [for s in var.subnets : {
name = s.name
prefix = s.prefix
}]
content {
name = subnet.value.name
address_prefix = subnet.value.prefix
}
}
}
Run Code Online (Sandbox Code Playgroud)
它似乎var.subnets已经与content块期望的对象结构兼容,因此可以通过直接访问它来进一步简化它:
dynamic "subnet" {
for_each = var.subnets
content {
name = subnet.value.name
address_prefix = subnet.value.prefix
}
}
}
Run Code Online (Sandbox Code Playgroud)
只要var.subnets已经是一个对象列表,这应该会产生相同的结果。
| 归档时间: |
|
| 查看次数: |
5014 次 |
| 最近记录: |