Home > Blockchain >  Automatically create multiple resources in terraform using count and regex
Automatically create multiple resources in terraform using count and regex

Time:09-28

I want to be able to create multiple resources in terraform using the "count" meta-argument and regex. Like for example in the below code, I want terraform to automatically look for vn1_name, vn2_name, and vn3_name in my tfvars file, without me having to declaring all those variables by hardcoding. Is there any way ?

resource "azurerm_virtual_network" "poc_vn" {
   count = 3
   name                = var.virtual_network.vn[1-3]_name ***(This is not valid syntax)***
   location            = azurerm_resource_group.poc_rg.location
   resource_group_name = azurerm_resource_group.poc_rg.name
   address_space       = var.virtual_network.vn1_address_space

     tags = {
      environment = var.virtual_network.env1_name
     }
  }

CodePudding user response:

try this syntax:

resource "azurerm_virtual_network" "poc_vn" {
   count = 3
   name                = "vnet-${count.index}"   
   location            = azurerm_resource_group.poc_rg.location
   resource_group_name = azurerm_resource_group.poc_rg.name
   address_space       = var.virtual_network.vn1_address_space

     tags = {
      environment = var.virtual_network.env1_name
     }
  }

The vnets name will be vnet-0, vnet-1, vnet-2.

More info about count here: https://www.terraform.io/language/meta-arguments/count

CodePudding user response:

The typical way to model something like this in Terraform is to declare a single variable that will capture all of the settings about the virtual network in a single data structure. For example:

variable "virtual_networks" {
  type = map(object({
    environment   = string
    address_space = string
  }))
}

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

resource "azurerm_virtual_network" "poc_vn" {
  for_each = var.networks

  name                = each.key
  location            = azurerm_resource_group.poc_rg.location
  resource_group_name = azurerm_resource_group.poc_rg.name
  address_space       = each.value.address_space

  tags = {
    environment = var.environments[each.value.environment].name
  }
}

The top-level namespace of variables is not a value itself, and so you can't treat it as one. However, you can declare a particular variable as having a collection type, such as the two map variables I showed above, and then you can dynamically look up elements in those maps using the indexing syntax.

  • Related