Search code examples
terraforminfrastructure-as-codehcl

Can I have a namespace or hierarchy for resources in terraform? Or otherwise group resources together?


As a specefic example, I have a group of subnets that are all used for the same thing, but are spread across multiple availabililty zones.

I'd like to be able to reference all of them as a list, so that I could do something like aws_subnet.myname[*].id to get all the subnet ids for that group of subnets.

Is there any way to do something like this?


Solution

  • There is no specialized feature for grouping resources, but you can do it yourself using a named local value:

    locals {
      subnets = flatten([aws_subnet.a, aws_subnet.b, aws_subnet.c])
    }
    

    The flatten call here is to normalize between resources with and without count set, since without count the resource expression returns just a single object while with count it is a sequence of instances.

    Then elsewhere in the configuration in situations where you need all of these ids together, you can write local.subnets[*].id.