'terraform override variables multiple modules with their environment specific variables

I have a terraform repo that contains multiple modules as below.

root
   |-modules
   |   |-module1
   |   |    |- main.tf
   |   |    |- variables
   |   |          |- dev.tfvars
   |   |          |- test.tfvars
   |   |          |- prod.tfvars
   |   |-module2
   |   |    |- main.tf
   |   |    |- variables
   |   |          |- dev.tfvars
   |   |          |- test.tfvars
   |   |          |- prod.tfvars
   |-main.tf

root's main.tf includes modules as below

 module "module1"{
    source = ./modules/module1
}

module "module1"{
    source = ./modules/module1
}

Now for this structure, I need to add environment specific tfvars file to provide variables needed for that module. I am able to override variables if it's a single module. But not able to figure out overrides in this case. Any advice is helpful.



Solution 1:[1]

You have to pass all those overwritten variables explicitly to your modules, start from the root.

Solution 2:[2]

I would restructure the project to take the environment specifics out of the modules. Modules should be environment agnostic.

root
   |-modules
   |   |-module1
   |   |    |- main.tf
   |   |    |- variables
   |   |-module2
   |   |    |- main.tf
   |   |    |- variables
   |-main.tf
   |- dev.tfvars
   |- test.tfvars
   |- prod.tfvars

pass the required vars to the module invocation

 module "module1"{
    source = ./modules/module1
    myvar1 = var.myvar1
    myvar2 = var.myvar2
}

module "module2"{
    source = ./modules/module2
    myvar1 = var.myvar1
    myvar2 = var.myvar2
}

then select the tfvars file for the environment you are deploying to

terraform plan -var-file=dev.tfvars

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcin
Solution 2 nick fox