Search code examples
terraformterraform-modules

Terraform - how to get a child module to call other child modules


I know this isn't best practice, as child modules should exist at the same level. But it doesn't seem impossible, but I can't figure out how.

I'm looking to have a root module -> call a child module -> calls a series of child modules.

The root module would contain specific details for the child module. The child module would essentially act as a template for my AWS infrastructure to ensure uniformity across my AWS accounts. The last set of child modules would contain the actual code to create the resources, such as EC2 instances, VPC, etc.

I've tried implementing a structure like this, but it treats the child module (the one I want to act as a template) as the root module, and completely ignores the values I've set in the root module.

I tried having variables with no defaults in the child modules and passing that value in the root module.

I've tried with no variable file in the child module (one acting as a template)

I've tried a terraform.tfvars in the root module

I don't have any terraform code attached as I'm really looking for the answer at a theoretical level.


Solution

  • Well given that there is no code example, the simple answer is that you have to use a source up the tree, means:

    for example if you have a root module that describe few properties and you want to get vpc_id from the child, you need to open a new module and use the root as the source, means, if we are in root:

    source = path_to_tf_module
    
    vpc_id = var.vpc_id
    

    make sure you have a variable with no value here

    and if you have child, let's say child-1:

    source = path_to_root
    
    vpc_id = var.vpc_id
    

    if you want to get the value from here just pass the value, if not, same as in the root add the variables in that file or in a variables.tf file in the same directory and do the same in chaild-2

    if you in chaild-2

    source = path_to_child-1
    
    vpc_id  = "value"
    

    every child will pass a parameter to the child up to the root.