Makram
Makram

Reputation: 843

Terraform on Azure - Deploy multiple subnet

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?

Upvotes: 1

Views: 7053

Answers (2)

Rajat Arora
Rajat Arora

Reputation: 606

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

Upvotes: 4

Lachie White
Lachie White

Reputation: 1251

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!

Upvotes: 1

Related Questions