Home > Enterprise >  How to add and reference a map of map as a local variable in terraform?
How to add and reference a map of map as a local variable in terraform?

Time:06-21

I want to create 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 "mumbai" {
  source                    = "./site-to-site-vpn-setup"
  providers                 = { aws = aws.mumbai }
  is_second_execution       = lookup(local.region_map, local.region_map["mumbai"]["is_second_execution"], false)
  cg_ip_address             = lookup(local.region_map, local.region_map["mumbai"]["cg_ip_address"], "")
}

but upon doing terrafrom plan the cg_ip_address is being set to null. Also If I add another module say "saopaulo" and I need to pass default values of is_second_execution and cg_ip_address for it without adding saopaulo in the map, how do I do that?

CodePudding user response:

The lookup built-in function [1] has the following syntax:

lookup(map, key, default)

Since you have a map of maps, that means that the first argument is the map (local.region_map.mumbai), the second is the key you are looking for (cg_ip_address) and the third argument is the default value. So in your case you have to change the lookup to this:

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

[1] https://www.terraform.io/language/functions/lookup

  • Related