5

I am trying to reference a variable declared inside a module to update another variable in the same module and i am unable to find a guide as to how i can reference the variable.

Here is my code sippet

module "cluster" {
  source = "..."

  var1 = value1    # directly passing value
  var2 = module.cluster.var1 # I need to update this variable value based on value of var1

I am facing below error during terraform plan

Terraform v1.0.11
on linux_amd64
Configuring remote state backend...
Initializing Terraform configuration...

 Error: Unsupported attribute
│ 
│   on main.tf line 04, in module "cluster":
│   04:       var2 = module.cluster.var1
│     ├────────────────
│     │ module.cluster is a object, known only after apply
│ 
│ This object does not have an attribute named "var1".

I have also tried using referencing using local.var1 shown below

module "cluster" {
  source = "..."

  var1 = value1    # directly passing value
  var2 = local.var1 # I need to update this variable value based on value of var1

and then i encounter below error

Terraform v1.0.11
on linux_amd64
Configuring remote state backend...
Initializing Terraform configuration...
╷
│ Error: Reference to undeclared local value
│ 
│   on main.tf line 04, in module "cluster":
│   04:       var2 = local.var1
│ 
│ A local value with the name "var1" has not been declared.
╵

any lead will be helpful.

Regards

1
  • You can both assign and use local values in the locals context, so it's surprising that you can't assign a value and use it in the same module context. There are cases where this forces error-prone duplication -- if you don't opt for the (even worse) external locals definition of the value. Commented May 8, 2023 at 23:36

1 Answer 1

5

Your second attempt, using a local variable, is on the right track, but you have to actually declare the local variable:

locals {
   var1 = value1
}

module "cluster" {
  source = "..."

  var1 = local.var1
  var2 = local.var1
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.