gpt4 book ai didi

azure - 如何使用 terraform 创建两个 VNET 并在每个 VNET 中创建一些子网

转载 作者:行者123 更新时间:2023-12-03 01:21:29 26 4
gpt4 key购买 nike

如何使用 terraform 动态创建两个 VNET 以及每个 VNET 中的一些子网?

目前,我正在创建四个单独的资源 2,每个资源用于 VNET 和子网。

我想在 tf 代码中仅使用一个用于 VNET 的资源 block 和一个用于子网的资源 block ,并让 terraform 选择说 VNET“测试”两个子网(test1-subnet、test2-subnet)和第二个 VNET 说“dev” “两个独立的子网(dev1-subnet、dev2-subnet)。

如何使用 terraform for azure Provider 实现此场景?

resource "azurerm_virtual_network" "example" {
name = "rest-network"
address_space = ["10.0.0.0/16"]
location = "eastus"
resource_group_name = "test-rg"
}

resource "azurerm_virtual_network" "example1" {
name = "test-network"
address_space = ["10.1.0.0/16"]
location = "eastus"
resource_group_name = "test-rg"
}

resource "azurerm_subnet" "example" {
name = "rest-subnet"
resource_group_name = "test-rg"
virtual_network_name = azurerm_virtual_network.example.name
address_prefix = "10.0.1.0/24"

enforce_private_link_endpoint_network_policies = true
}

resource "azurerm_subnet" "example1" {
name = "test-subnet"
resource_group_name = "test-rg"
virtual_network_name = azurerm_virtual_network.example1.name
address_prefix = "10.1.1.0/24"

enforce_private_link_endpoint_network_policies = true
}

最佳答案

您必须参数化您的设置。一种方法可能如下(您可能需要修改该示例以满足您的特定需求):

variable "vnets" {
default = {
test = {
address_space = ["10.0.0.0/16"]
resource_group_name = "test-rg"
subnets = [{
address_prefix = "10.0.1.0/24"
},
{
address_prefix = "10.0.2.0/24"
}
]
},
dev = {
address_space = ["10.1.0.0/16"]
resource_group_name = "dev-rg"
subnets = [{
address_prefix = "10.1.1.0/24"
},
{
address_prefix = "10.1.2.0/24"
}
]
}
}
}


locals {
# flatten the var.vnets variable
vnet_subnet_map = merge([
for vnet_name, vnet_details in var.vnets:
{
for idx, subnet in vnet_details.subnets:
"${vnet_name}-${idx}" => {
vnet_name = vnet_name
subnet_name = "${vnet_name}${idx}-subnet"
address_space = vnet_details.address_space
resource_group_name = vnet_details.resource_group_name
subnet_address_prefix = subnet.address_prefix
}
}
]...) # do NOT remove the dots
}

然后创建两个 vnet 及其子网:

resource "azurerm_virtual_network" "vnet" {

for_each = var.vnets

name = "${each.key}-network"
address_space = each.value.address_space
location = "eastus"
resource_group_name = each.value.resource_group_name
}



resource "azurerm_subnet" "subnet" {

for_each = local.vnet_subnet_map

name = each.value.subnet_name
resource_group_name = each.value.resource_group_name
virtual_network_name = azurerm_virtual_network.vnet[each.value.vnet_name].name
address_prefix = each.value.subnet_address_prefix

enforce_private_link_endpoint_network_policies = true
}

关于azure - 如何使用 terraform 创建两个 VNET 并在每个 VNET 中创建一些子网,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70002667/

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