Chained for_each modules

Hi there, I understand that when using for_each in modules, you can either use a map whose keys are known, or a set of strings. I’m having difficulty being able to use for_each but chained with another module using for_each, so I’m wondering if it’s even possible. For example:

module “a”

variable "name" {}

resource "some_resource" "example" {
  name = var.name
}

output "name" {
  value = some_resource.example.name
}

output "id" {
  value = some_resource.example.id
}

module “b”

variable "name" {}
variable "resource_id" {}

resource "other_resource" "example" {
  name = var.name
  resource_id = var.resource_id
}

main.tf

# this works fine
module "all_resources" {
  source = "./modules/a"
  for_each = ["one", "two"]
  name = each.value
}

# this doesn't
module "chained_resources" {
  source = "./modules/b"
  for_each = ???? # want to create one per those created by module.all_resources
  name = each.value.name
  resource_id = each.value.id
}

In my use case I actually need a couple attributes from module.all_resources, so it seems natural to use a map/object, but I can’t figure out how to generate known keys in that case. If I use a list, I’m not sure how I could retrieve multiple attributes from module.all_resources

Hi @alexgagnon,

I would expect the following to do what you described:

module "chained_resources" {
  source   = "./modules/b"
  for_each = module.all_resources

  name        = each.value.name
  resource_id = each.value.id
}

There’s a more elaborate example of this sort of thing in the documentation section Chaining for_each Between Resources. The example is for resources rather than modules, but the effect is the same in both cases.