Multiple iteration in one resource

The trick is to somehow make yourself a map that you can use with for_each, that does the right thing, which means you need:

  • Map keys, at the top level of the map, which are distinct and give a consistent name to each resource you want to create
  • Map values, which provide you with all of the varying information you need to fill in the resource attributes

For example, and using range(12) to model the instances so I don’t have to set up the AWS provider locally:

merge([
    for port, proto in var.port_forwarding_config :
    {
      for instance in range(12) : "${port}_${proto}_${instance}" => {
        port     = port
        proto    = proto
        instance = instance
      }
    }
  ]...)

(You might replace range(12) with aws_instance.instance[*].id for example.)