gpt4 book ai didi

azure - 使用 Terraform 的同一 VNet 中的多个子网

转载 作者:行者123 更新时间:2023-12-02 08:18:25 24 4
gpt4 key购买 nike

我对 terraform 完全陌生,我正在尝试学习和编写 TF 代码来自动化 Azure VM 部署。我试图将每个部分作为模块(rg 除外)来覆盖,而不是将其保存在单个 main.tf 文件中。我的目的是创建 1 个 vnet (TESTVNET) 并在同一 Vnet 中创建多个子网,我可以在 tfvars 文件中定义子网名称和地址。

我能够到达 VNet 上的创建,但无法循环遍历定义的子网

请仔细阅读我的代码。文件Main.tf

    resource "azurerm_resource_group" "resource_group" {
name = var.RGname
location = var.RGlocation
}

module "VNET" {
source = "./Modules/NetworkConfig"
name = var.VNETname
address_space = var.address_space
location = var.RGlocation
resource_group_name = azurerm_resource_group.resource_group.name
}

module "SUBNETS" {
source = "./Modules/SubnetConfig"
Subnetlist = var.Subnetlist
virtual_network_name = module.VNET.vnet_name
resource_group_name = azurerm_resource_group.resource_group.name
depends_on = [azurerm_resource_group.resource_group, module.VNET.vnet]

}

Variables.tf (of main)

variable "RGlocation" {
}

variable "RGname" {
}

variable "VNETname" {
}

variable "address_space" {
}

variable "Subnetlist" {
type = map(object({
name = list(string)
address = list(string)
}))
}

文件main.tfvars

    RGlocation = "westus"
RGname = "TEST-RG1"

VNETname = "TEST-VNET-01"
address_space = "10.0.0.0/16"


Subnetlist = {
"list" = {
name = ["TESTSUBNET","TESTSUBNET1","TESTSUBNET2"]
address = ["10.0.1.0/24","10.0.2.0/24","10.0.3.0/24"]
}
}

文件Subnets.tf(模块)

    resource "azurerm_subnet" "SUBNETS" {
for_each=var.Subnetlist
name=each.value.name
address_prefixes=each.value.address
resource_group_name = var.resource_group_name
virtual_network_name = var.virtual_network_name

}

文件variable.tf(子网模块)

    variable "resource_group_name" {
}

variable "virtual_network_name" {
}

variable "Subnetlist" {
type = map(object({
name = list(string)
address = list(string)
}))
}

下面是我遇到的错误


│ Error: Incorrect attribute value type

│ on Modules\SubnetConfig\Subnet.tf line 3, in resource "azurerm_subnet" "SUBNETS":
│ 3: name=each.value.name
│ ├────────────────
│ │ each.value.name is list of string with 3 elements

│ Inappropriate value for attribute "name": string required.

谁能告诉我如何解决这个问题吗?另外,如果这不是正确的方法,请告诉我。

最佳答案

您迭代Subnetlist的方式不正确 - 您只获得“list”键的值,最终得到一组子网而不是单个项目。使其成为单个子网对象的映射:

variable "Subnetlist" {
type = map(object({
name = string
address = string
}))
}

然后将其传递到 tfvars 中,例如:

Subnetlist = {
"s1" = { name = "TESTSUBNET", address = "10.0.1.0/24" },
"s2" = { name = "TESTSUBNET1", address = "10.0.2.0/24" },
"s3" = { name = "TESTSUBNET2", address = "10.0.3.0/24" }
}

最后在模块中使用它,如下所示:

resource "azurerm_subnet" "SUBNETS" {
for_each = var.Subnetlist
name = each.value.name
address_prefixes = each.value.address
resource_group_name = var.resource_group_name
virtual_network_name = var.virtual_network_name
}

关于azure - 使用 Terraform 的同一 VNet 中的多个子网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71006812/

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