Need to Call child Module with variable as attribute

I have a requirement to launch vm with frontend and backend subnet in for_each loop.
in order to make code more sleek i am trying to use module with variable in vm.tf file
but its not working. Please refer the following vm.tf code.

vm.tf subnet_section:

 subnets = [
   {
      subnet_id = [for internal_network in var.networks : module[(internal_network)].subnet.id if internal_network == each.value.subnet]
      ip_address = each.value.private_ip
   }
 ]

while using above logic getting following error.

The "module" object cannot be accessed directly. Instead, access one of its attributes.

Need help to solve the problem so that i can use for_each loop to automate VM creation
corresponding to front_end or back_end vm should be launch automatically.

It is not possible to dynamically reference modules in this way.

References to Values - Configuration Language | Terraform by HashiCorp :

Although many of these names use dot-separated paths that resemble attribute notation for elements of object values, they are not implemented as real objects. This means you must use them exactly as written: you cannot use square-bracket notation to replace the dot-separated paths, and you cannot iterate over the “parent object” of a named entity;

module.<MODULE NAME> is an value representing the results of a module block.

I believe this is because Terraform needs to build the dependency graph between resources, before it starts evaluating dynamic expressions.

1 Like