Looping using multiple data resource values

Currently, I have an outputs with AWS subnet IDs Like this

subnets            = {
      + GPS     = [
          + "subnet-0b8d3d38456431efd",
          + "subnet-0678f4a68a7517d15",
          + "subnet-030f9b726908f6fa1",
        ]
      + admin   = [
          + "subnet-073346e287fd0070c",
          + "subnet-05865fb67386d2fb9",
          + "subnet-04b27673caad2e651",
        ]
      + data    = [
          + "subnet-0aeb9d129d278f363",
          + "subnet-0fdac331bf0c1221e",
          + "subnet-0c44442616e51b459",
        ]
      + private = [
          + "subnet-08a6934c70fde452c",
          + "subnet-04abb86d569d30bbc",
          + "subnet-0fcc9113742ffb4fe",
        ]
      + public  = [
          + "subnet-02862107c9307838b",
          + "subnet-0c8154cc71a9566c9",
          + "subnet-09ce42aa351e803c3",
        ]
    }

Since in AWS, each subnet has a corresponding route table ID. I would like to get it’s corresponding route table ID and store it in a different list like for example:

route_tables = {
    GPS = ["rt-xxx", "rt-xxx", "rt-xx"],
    data = ["rt-xxx", "rt-xxx", "rt-xx"],
    admin = ["rt-xxx", "rt-xxx", rt-xx"],
    public = ["rt-xxx", "rt-xxx", "rt-xx"],
    private = ["rt-xxx", "rt-xxx", "rt-xx"]
}

I would like to know if that is possible by using the data resource for aws_route_table
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/route_table#subnet_id

To do exactly what you’re describing would be difficult - and probably too messy to be a good solution, if successfully implemented.

The problem, is that the for_each looping construct for data and resource blocks needs a single flat collection to loop over.

Flattening it is fine - there’s a flatten() function - https://www.terraform.io/language/functions/flatten - but rebuilding a multi-layer data structure from the results is the difficult/messy bit.

I would suggest you instead expose your route_tables output as a single map from subnet ID to route table ID. This will be much easier to construct from the data resource, and should still enable your users to do the same tasks - accessing all route table IDs in a specific group will just require starting by getting the subnet IDs in the group, and then looping them up in the route_tables map.