1

I have a directory structure of my project as follows;

|
|- module1
|   |- module1_main.tf
|
|- module2
|   |- module2_main.tf
|
|- main.tf
|- locals.tf

in main.tf I am using both modules (module1 & module2). However, both of these modules contain a parameter which is common, and I need it configurable. So I'm thinking of using a local variable for that.

I have tried the following:

locals.tf at root level:

locals {
  common_variable = "myValue"
}

main.tf at root level:

module "instance_module_1" {
  source = "./module1"
  parameter_module_1 = local.common_variable
}

module "instance_module_2" {
  source = "./module2"
  parameter_module_2 = local.common_variable
}

This approach requires me to introduce new variables inside the modules as follows: module1_main.tf:

variable "parameter_module1" {}

resource "some_resource" "some_resource_name" {
  ..<required parameters>..
  some_specific_parameter = var.parameter_module1
}

module2_main.tf:

variable "parameter_module2" {}

resource "some_resource" "some_resource_name" {
  ..<required parameters>..
  some_specific_parameter = var.parameter_module2
}

I want to know is there any other way for me to directly access the local variable I defined at root level in my .tf files of modules (instead of defining separate variables inside each module). something like:

module1_main.tf:

resource "some_resource" "some_resource_name" {
  ..<required parameters>..
  some_specific_parameter = local.common_variable
}

Open to your suggestions and best practices. :)

3
  • 1
    You cannot do that, that's why they are called local variables. If you really need to use local variables, you can define them at the module level as well.
    – Marko E
    Commented Feb 23, 2023 at 7:27
  • 1
    Thanks for the comment. If I go to define local variables at the module level, I won't be able to change all of them from a single place. That is why I brought up this question to see whether there is any way to do it. Commented Feb 23, 2023 at 8:23
  • 1
    Depending on what the "common variable" is doing, there might be other ways of achieving the same thing. For example, if that is a tag, you can define it on the provider level. If that value will be the same for all module calls then it might be better to define a regular variable on the module and set its default value to that value you want to have across all of them.
    – Marko E
    Commented Feb 23, 2023 at 8:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.