dataviews
dataviews

Reputation: 3100

terraform access variable using module variable key

If I have a variables in my terraform module, such as:

variable "environment" {
  type = string
}

within my module, I'm using locals to define some items specific to environments:

locals {
  dev = {
    foo=bar
  }
}

Within the module where locals is, how can I use the passed in environment variable to access the corresponding key in locals?

locals.${var.environment}.foo is what I'm going to, where var.environment will evaluate to dev.

Something like this?

local[var.environment]["foo"]

Upvotes: 0

Views: 469

Answers (1)

Fcmam5
Fcmam5

Reputation: 6832

You can't access the locals object directly. So this won't work

local[var.environment]["foo"]

And it will produce this error:

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

Instead, you can create a local map with your environments as keys:

locals {
  a_meaningful_name = {
    dev = {
      greeting = "Welcome to DEV"
    }
    uat = {
      salutations = "Hello from UAT"
    }
  }
}

variable "environment" {
  type = string
}

output "rs" {
  value = local.a_meaningful_name[var.environment]
}

Upvotes: 1

Related Questions