Tamerz
Tamerz

Reputation: 947

How can you access elements from a nested map with user supplied variable?

I'm trying to figure out the best way to look up multiple values from a mapped variable depending on an input variable. In this case, the input would be the name of a vSphere switch port group.

For instance, given this information:

variable "networks" {
    type    = map
    default = {
        "port-group-mail.internal" = {
            network = "10.0.10.0"
            netmask = "24"
            gateway = "10.0.10.1"
        }
        "port-group-web.dmz" = {
            network = "10.0.50.32"
            netmask = "27"
            gateway = "10.0.50.33"
        }
    }
}

For usage:

module "myvm" {
  vm_name = "web-01"
  network = "port-group-web.dmz"
}

I'd want to be able to look up "network", "netmask", "gateway" based on that network variable from my module.

Upvotes: 0

Views: 65

Answers (1)

yvesonline
yvesonline

Reputation: 4837

Consider the following variable (this is basically your network module variable):

variable "my_network" {
    type    = string
    default = "port-group-web.dmz"
}

Now if I do var.networks[<my variabl>] I can access the map:

$ terraform console
> var.my_network
"port-group-web.dmz"
> var.networks[var.my_network]
{
  "gateway" = "10.0.50.33"
  "netmask" = "27"
  "network" = "10.0.50.32"
}

Upvotes: 2

Related Questions