Variable name reference with each.key


I have a requirement where I need dynamically lookup variable names,
So I have variables like this,

variable "app_example_secret" {
  type        = string
  description = "API Secret"
  sensitive   = true

Assuming one of the each.key is “app_example”, how do I refer to the variable “app_example_secret” with an “each.key” reference?

Code that is looking for a such an interpolation is,

"KeySecret" : try(module.app_yaml.files[each.key].app.exists, "var.${each.key}_secret", local.secret[each.key])

Obviously the above doesn’t work as it creates a static

+ KeySecret        = "var.app_example_secret"

I tried referring to it like this,


That throws “An attribute name is required after a dot.” error.

Appreciate your help on this.

This isn’t possible. Variable references have to be static.

If there are only a limited selection of possible variables you could create a map:

locals {
  some_map = {
    var1 = var.var1
    var2 = var.var2

"keySecret" = local.some_map[var.var_lookup]

Thank you for the suggestion @stuart-c .
I created a map like this,

existing_apps = {
    "app_example" = {
      secret = var.app_example_secret

And was able to lookup like this,

try(module.app_yaml.files[each.key].app.exists, false) == true ? local.existing_apps[each.key].secret : local.secret[each.key]

Thank you. Appreciate your help!