0

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"]
1
  • Are there any errors or have you tried any of those? Commented Feb 3, 2023 at 15:41

1 Answer 1

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.