Home > OS >  How do I loop through te below given variable in terraform
How do I loop through te below given variable in terraform

Time:02-06

I am trying to create vnets for multiple environments using one single variable. I am not quite sure if it is possible. My variable is given below

azure_vnets = {
  Prod = [
    {
      cidr = "10.10.0.0/24"
      vnet_name = "prod-vnet1"
      dns  = "10.10.0.1"
      rg   = "prodrg1"
      location = "eastus"
    },
    { 
      cidr = "10.10.1.0/24"
      vnet_name = "prod-vnet2"
      dns  = "10.10.0.2"
      rg   = "prodrg2"
      location = "eastus"
    }     
  ],
  nonProd = [
     {
      cidr = "10.10.0.0/24"
      vnet_name = "nonprod-vnet1"
      dns  = "10.10.0.1"
      rg   = "nonprodrg1"
      location = "eastus"
    },
    { 
      cidr = "10.10.1.0/24"
      vnet_name = "nonprod-vnet2"
      dns  = "10.10.0.2"
      rg   = "nonprodrg2"
      location = "eastus"
    }    
  ]
}

So as to create multiple vnets from this

resource "azurerm_virtual_network" "this" {
for_each = xxx
name = each.xxx
xxxx
xxx
}

CodePudding user response:

You have to flatten it first:


locals {
  flat_azure_vnets = merge([
      for env_name, env_vn_list in var.azure_vnets:
         {
           for idx, env_vn in env_vn_list:
             "${env_name}-${idx}" => env_vn
         }
    ]...)
}

then you use it:

resource "azurerm_virtual_network" "this" {
  for_each = local.flat_azure_vnets
  name = each.value["vnet_name"]
  xxxx
  xxx
}
  •  Tags:  
  • Related