Terraform on Azure - Deploy multiple subnet

混江龙づ霸主 提交于 2020-02-25 13:17:09

问题


I'm trying to implement a Terraform script to create multiple subnets.

resource "azurerm_subnet" "test_subnet" {
    name = "testSUBNET"
    resource_group_name = "${local.resource_group_name}"
    virtual_network_name = "${azurerm_virtual_network.lab_vnet.name}"
    address_prefix = "10.0.1.0/24"
}

Is there a way to do a for-each or a loop on a variable in order to create them at the same time?

Best Regards!


回答1:


You can achieve this using a variable and count index as follows:

variable "subnet_prefix" {
  type = "list"
  default = [
    {
      ip      = "10.0.1.0/24"
      name     = "subnet-1"
    },
    {
      ip      = "10.0.2.0/24"
      name     = "subnet-2"
    }
   ]
}

resource "azurerm_subnet" "test_subnet" {
    name = "${lookup(element(var.subnet_prefix, count.index), "name")}"
    count = "${length(var.subnet_prefix)}"
    resource_group_name = "${local.resource_group_name}"
    virtual_network_name = "${azurerm_virtual_network.lab_vnet.name}"
    address_prefix = "${lookup(element(var.subnet_prefix, count.index), "ip")}"
}

There is also preview feature available for-each in the new version




回答2:


If you are using Terraform 12 this can be achieved using the for-each capability or the count capability

count should be used if you are looking to create almost identical resources.

for-each should be used to create multiple of each instance based on a different map or set of values.

Using an list of strings and the toset() function to convert this is a neat way to achieve this

variable "subnet_ids" {
  type = list(string)
}

resource "aws_instance" "server" {
  for_each = toset(var.subnet_ids)

  ami           = "ami-a1b2c3d4"
  instance_type = "t2.micro"
  subnet_id     = each.key # note: each.key and each.value are the same for a set

  tags = {
    Name = "Server ${each.key}"
  }
}

Or you could achieve this by using something like the below:

resource "azurerm_resource_group" "rg" {
  for_each = {
    a_group = "eastus"
    another_group = "westus2"
  }
  name     = each.key
  location = each.value
}

If you are looking to achieve this with Terraform 11 the count and variable capabilities are the only way other than code duplication. (Rajat Arora has mentioned)

I would strongly recommended using Terraform 12 as the providers for Terraform 11 will be unsupported in the not to far future and if you can save yourself from refactoring now, you should!



来源:https://stackoverflow.com/questions/59681957/terraform-on-azure-deploy-multiple-subnet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!