Module composition with for_each conditional

Viewed 31

On my root module, I am declaring two modules (paired_regions_network and paired_regions_app), that both iterate a set of regions.

module "paired_regions_network" {
  source                  = "./modules/network"
  application_hostname    = ["${module.paired_regions_app.website_hostname}"]  // THIS IS BREAKING THE CODE
  ...
  for_each = (var.environment == "TEST" || var.environment == "PROD") ? var.paired_regions : { region1 = var.paired_regions.region1 }
}

module "paired_regions_app" {
  source                  = "./modules/multi-region"
  ...
  for_each = (var.environment == "TEST" || var.environment == "PROD") ? var.paired_regions : { region1 = var.paired_regions.region1 }
}

output "network_outputs" {
  value = module.paired_regions_network
}

output "app_outputs" {
  value = module.paired_regions_app
}

The iterated regions are declared as follows:

variable "paired_regions" {
  description = "The paired regions"
  default = { 
    region1 = { 
      ...
    },
    region2 = { 
      ...
    }
  }
}

From the paired_regions_network module I want to have access to the output coming from the paired_regions_app module, namely the website_hostname value, which I want to assign to the application_hostname parameter, of the paired_regions_network module, as shown above.

output "website_hostname" {
  value       = azurerm_app_service.was_app.default_site_hostname
  description = "The hostname of the website"
}

How can I change the line below, so that I am able to access the outputted website hostname by the other module?

  application_hostname    = ["${module.paired_regions_app.website_hostname}"]

With the above code, I am getting this error:

│ Error: Unsupported attribute
│
│   on main.tf line 24, in module "paired_regions_network":
│   24:   application_hostname    = ["${module.paired_regions_app.website_hostname}"]
│     ├────────────────
│     │ module.paired_regions_app is object with 2 attributes
│
│ This object does not have an attribute named "website_hostname".
1 Answers

Since you are using for_each in paired_regions_app you have to access its outputs by key.

application_hostname    = [module.paired_regions_app[each.key].website_hostname]
Related