Home > Mobile >  what is correct way of reference to value in object/map type value in terraform
what is correct way of reference to value in object/map type value in terraform

Time:08-15

Objective: To assign particular key value while creating resource

Variable.tf:

variable "vnet_address_space" {
    type = map(list(string))
    default = {
        "Dev"  = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
        "Stage" = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
        "Prod" = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
    }
}

Now I use below code to create VNET with address space based on environment i.e Dev,Stage,Prod etc

resource "azurerm_virtual_network" "vnet" {
  name                = var.hub_vnet_name
  location            = azurerm_resource_group.rg[0].location
  resource_group_name = azurerm_resource_group.rg[0].name
  for_each = {for k,v in var.vnet_address_space: k=>v if k == "Dev"}
  address_space       =  var.vnet_address_space.Dev
  dns_servers         = var.dns_servers
  tags     = {
    environment = "${var.env}"
    costcentre = "14500"
  }
  dynamic "ddos_protection_plan" {
    for_each = local.if_ddos_enabled

    content {
      id     = azurerm_network_ddos_protection_plan.ddos[0].id
      enable = false
    }
  }
}

Error:

Error: Invalid value for input variable
│ 
│   on /home/circleci/workingfiles/*********output.tfvars.json line 15:
│   15:   "vnet_address_space": [
│   16:     "xx.xx.0.0/24",
│   17:     "xx.xx.0.0/20",
│   18:     "xx.xx.0.0/24",
│   19:     "xx.xx.0.0/20"
│   20:   ],
│ 
│ The given value is not suitable for var.vnet_address_space declared at variables.tf:25,1-30: map of list of string required.
╵

How Should I tell Terraform, take Dev Address space in variable and create vnet ?

Please help

CodePudding user response:

The error means that your output.tfvars.json is incorrect. It has nothing to do with your azurerm_virtual_network. In your output.tfvars.json you should have:

vnet_address_space = {
        "Dev"  = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
        "Stage" = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
        "Prod" = ["xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/24","xx.xx.0.0/20"]
    }
  • Related