sebastian
sebastian

Reputation: 2348

How to access a local using a variable in Terraform

I have the following code.

mymodule

variable "senses" {
  type = string
}


locals {
  sounds = {
    "cat" = "meow"
    "dog" = ["bark", "woof"]
  }
}

output "noise" {
  value = local[var.senses]["cat"]
}


call mymodule

module "mymodule" {
  source = "../../../modules/mymodule"
  senses = "sound"
}

returns error:

Error: Invalid reference

  on ../../../modules/mymodule/outputs.tf line 62, in output "noise":
  62:   value = local[var.senses]["cat"]

The "local" object cannot be accessed directly. Instead, access one of its
attributes.

my code can't seem to handle

value = local[var.senses]["cat"]

Any suggestions on how i can get this to work?

Upvotes: 4

Views: 5282

Answers (1)

STW
STW

Reputation: 46366

I don't believe it's possible to use a variable to switch which local you're reading. I.e. local[var.senses] is the root of the issue.

If you refactor slightly and put your values inside a single, known, value--such as local.senses it should then let you do a key lookup within that value.

So, if you modify your locals to place your values in a senses key:

locals {
  senses = {
    "sounds" = {
      "cat" = "meow"
      "dog" = ["bark", "woof"]
    }
  }
}

and update your lookup to use that field:

value = local.senses[var.senses]["cat"]

Then I believe it will work, since your are doing a key lookup against a specific local rather than trying to dynamically select the local.

Upvotes: 3

Related Questions