How to loop on resource name?

Hello,

In a resource I have 3 attribute “router”, like this :

 router {
    router_id     = flexibleengine_vpc_v1.prod.id
  }

  router {
    router_id     = flexibleengine_vpc_v1.preprod.id
  }

  router {
    router_id     = flexibleengine_vpc_v1.dev.id
  }

I’d like to make a “dynamic” router, something like :

  dynamic "router" {
    for_each = var.vpc_list
    iterator = item
    content {
      router_id = flexibleengine_vpc_v1.????.id
    }
  }

So it will be parameterized from production.tfvars :

vpc_list = {
  "prod" = {},
  "preprod" = {},
  "dev" = {},
  "new_vpc" = {}
}

Does someone know if it’s possible ? If so, how to fill the “???” ?
thanks,

Hi @aurelien.samson,

You will need to first gather your resource instances into a mapping so you can look them up dynamically by key:

locals {
  vpcs = {
    prod   = flexibleengine_vpc_v1.prod
    preprod = flexibleengine_vpc_v1.preprod
    dev    = flexibleengine_vpc_v1.dev
  }
}

Inside your dynamic "router"'s content block, you can refer to the corresponding VPC ID by looking up by the current key:

router_id = local.vpcs[item.key].id