How to call a function that has a global variable in its path?

Hi,

I have a global variable “var.region”.

And I also have a function:

locals {
   region_lookup = {
      amr = {
              service_1="service-1"
              service_2="service-2"
         }
       eu = {
              service_1="service-1"
              service_2="service-2"
         }
       apac = {
             service_1="service-1"
             service_2="service-2"
       }
   }
}

The global variable region has two values: apac, amr and eu. Now how do I call this region_lookup function?
I have tried: region_lookup.${var.region}.service_1 and region_lookup.[var.region][service_1] but neither worked.

Thanks

Local variables must be prefixed with local. when referenced, like local.region_lookup[var.region]["service_1"]

1 Like

Thanks for replying to me. I missed “local.” in the original post.

When I tried: service=${local.region_lookup.[var.region][“service_1”]}, the TF format tool gives me “An attribute name is required after a dot.” error.

Closet I could get was something like: service=${local.region_lookup[var.region][service_1]} though this gives me the “A reference to a resource type must be followed by at least one attribute access, specifying the resource name.” error…

Just lose the ${}.

1 Like

You don’t have a function, because the Terraform language doesn’t support the concept of functions - what you have is a local variable containing some nested objects.

Both of these have an incorrect ${ } enclosing the expression, as @macmiranda pointed out.

Additionally, the first contains an incorrect extra . whilst the second is missing some necessary quotes.

Taking a little from one, a little from the other, a correct version would be:

  service = local.region_lookup[var.region]["service_1"]

or you could also write it as

  service = local.region_lookup[var.region].service_1
2 Likes

Thank you both for the detailed explanation! :heart:
After editing the missing portion,

  service = local.region_lookup[var.region]["service_1"]

worked!