List of subnets while creating them in the same plan

For “maintenance” reasons, I am trying to get a list of specified AWS subnets. This way, I could add subnets to my files, and they would join the list on their own if correctly specified (with a specific tag for example).

So I tried to data the subnets, however they are created within the same terraform files, therefore cannot be loaded. I thought about adding “depends_on”, but that mean I would have to add the new ones explicitly, that’s exactly what I am trying to avoid.

Could I simply “declare” a list where I could put my subnets, like a variable but depending on resources creation?

Am i trying something I should not? Should I simply abandon this idea?

Hi @eliob83,

Without some specific code examples it’s hard to give specific advice, but the general pattern I would suggest here is dependency inversion: instead of making your module that uses the subnets go and fetch the subnets itself, have it instead receive them via an input variable, which can then be populated either from the aws_subnet managed resource type or the aws_subnet data source depending on whether it’s already known in the configuration.

Funnily enough the example in the dependency inversion docs section I linked above is already using AWS subnets to illustrate! For the sake of your question specifically though, a key part is that the variable where you’ll pass through the subnet ids passes through the dependency along with the value. So if you have a calling module like the one shown in that doc section…

module "consul_cluster" {
  source = "./modules/aws-consul-cluster"

  vpc_id     = aws_vpc.example.id
  subnet_ids = [for s in aws_subnet.example : s.id]
}

…then inside that module, any reference to var.vpc_id will indirectly depend on aws_vpc.example.id and any reference to var.subnet_ids will indirectly depend on aws_subnet.example, causing the operations to still happen in the correct order.

I expect the above might be too general to apply to your specific case. If so, please share some examples from your real configuration and what happened when you tried them, and then I can hopefully suggest some changes that will address your specific problem.