Create k8s cluster per subnets using for_each

Hi folks.
So what I’m trying to do is that I’m creating a vpc with 3 subnets and now I want to create one kubernetes cluster in each subnet. VPC-subnets and kubernetes cluster are defined as modules. The problem is that I cannot relate these two modules together. For example, this is how my looks like:

module "vpc_subnet" {
  source = "./modules/vpc_subnets"

module "otc_cce_cluster" {
  source = "./modules/k8s"
  for_each = module.vpc_subnet.subnet_id
  vpc_id = module.vpc_subnet.vpc_id
  subnet_id = module.vpc_subnet.subnet_id
  depends_on = [

But then the error says:

 Error: Unsupported attribute
│   on line 11, in module "otc_cce_cluster":
│   11:   for_each = module.vpc_subnet.subnet_id
│     ├────────────────
│     │ module.vpc_subnet is a object, known only after apply
│ This object does not have an attribute named "subnet_id".

The arrangement of my folders are like so:

| |
| |
| |
| |

I’m wondering if there is any solid example of doing such a thing or a quick tip how to move forward.

Terraform for_each does not operate on unknown keys (see documentation).

The keys of the map (or all the values in the case of a set of strings) must be known values , or you will get an error

IIRC the workaround is to transform module.vpc_subnet.subnet_id into a new data structure which has predefined keys.

Thanks for the reply.

However I managed to make it work to some extent. It means now the clusters are being created. Now I’m stuck at getting the cluster_id of each cluster. And because these are all references in the references, the code is getting confusing!