Home > Enterprise >  How to set default value for a field when referencing a value not in map of map?
How to set default value for a field when referencing a value not in map of map?

Time:06-21

I have a map of map as a local variable. I am using this

locals {
  region_map = {
     mumbai = {
       is_second_execution = true
       cg_ip_address       = "ip.add.re.ss"
    }
  }
}

Now I am referencing it as

module "saopaulo" {
  source                    = "./site-to-site-vpn-setup"
  providers                 = { aws = aws.saopaulo }
  is_second_execution       = lookup(local.region_map, local.region_map["saopaulo"]["is_second_execution"], false)
  cg_ip_address             = lookup(local.region_map, local.region_map["saopaulo"]["cg_ip_address"], "")
}

but since I have not added saopaulo in the map, I get an error. I want to set the fields is_second_execution and cg_ip_address to default values without adding saopaulo in the map so how do I do that?

The error I get is -

Error: Unsupported attribute
│ 
│  on main.tf line 20, in module "saopaulo":
│  20:  is_second_execution    = lookup(local.region_map.saopaulo, "is_second_execution", false)
│   ├────────────────
│   │ local.region_map is object with 1 attribute "mumbai"
│ 
│ This object does not have an attribute named "saopaulo".

CodePudding user response:

There are few ways of doing that. But I think in your particular case, easiest could be to use try, instead of lookup:

module "saopaulo" {
  source                    = "./site-to-site-vpn-setup"
  providers                 = { aws = aws.saopaulo }
  is_second_execution       = try(local.region_map["saopaulo"]["is_second_execution"], false)
  cg_ip_address             = try(local.region_map["saopaulo"]["cg_ip_address"], "")
}

Basically, try returns the first value which does not error out.

  • Related