我想使用Terraform和变量在多个虚拟网络中创建多个子网

时间:2019-08-06 18:42:07

标签: terraform terraform-provider-azure

示例: 我想使用变量创建2个vnet,并在一个vnet中创建2个子网,1个vnet和3个子网。

1 个答案:

答案 0 :(得分:0)

根据您的要求,此处的示例代码:

variable "vnet_address_space" {
  default = "10.0.0.0/16"
}

variable "subnet_prefix" {
    default = [
        "10.0.1.0/24",
        "10.0.2.0/24"
    ]

}

resource "azurerm_resource_group" "test" {
  name     = "testResourceGroup1"
  location = "East US"
}

resource "azurerm_virtual_network" "test" {
  name                = "acceptanceTestVirtualNetwork1"
  address_space       = ["${var.vnet_address_space}"]
  location            = "${azurerm_resource_group.test.location}"
  resource_group_name = "${azurerm_resource_group.test.name}"
}

resource "azurerm_subnet" "test" {
  count                = "${length(var.subnet_prefix)}"
  name                 = "testsubnet-${count.index}"
  resource_group_name  = "${azurerm_resource_group.test.name}"
  virtual_network_name = "${azurerm_virtual_network.test.name}"
  address_prefix       = "${element(var.subnet_prefix, count.index)}"
}

您可以使用相同的格式创建另一个Vnet,并根据需要更改其中的某些内容。