# Multiple iteration in one resource

**URL:** <https://discuss.hashicorp.com/t/multiple-iteration-in-one-resource/38612>\
**Category:** Terraform\
**Created:** [April 22, 2022, 9:35am UTC](https://discuss.hashicorp.com/t/multiple-iteration-in-one-resource/38612 "2022-04-22T09:35:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sya](https://avatars.discourse-cdn.com/v4/letter/s/e47774/32.png) [@Sya](https://discuss.hashicorp.com/u/Sya)\
**Post date:** [April 22, 2022, 9:35am UTC](https://discuss.hashicorp.com/t/multiple-iteration-in-one-resource/38612/1 "2022-04-22T09:35:29Z")

</div>

In this setup, is it possible to attach all 12 instance all together in aws\_lb\_target\_group\_attachment. I tried count, but it is throwing error saying we cannot use both. Then I tried `target_id = [for ids in aws_instance.instance : ids]`, here also error as it is tuple and string is expected. Even tried to convert each value to string. Is there any way to do it.

````nohighlight
  count = length(data.aws_ami_ids.api_mainapp_ami.*.ids)
  ami = element(data.aws_ami_ids.api_mainapp_ami.*.ids[count.index], 12)
  instance_type = "t3.xlarge"
  associate_public_ip_address = true
  vpc_security_group_ids = [var.secgroup]
  subnet_id = "${element(var.vpc_subnets_priv_id, count.index)}"
  tags = {
    Name = "${var.component}-${count.index+1}"
  }

}

LB.....

variable "port_forwarding_config" {
  default = {
      8900 = "TCP"
      7879 = "TCP" 
      80 = "TCP"
      9690 = "TCP"
  }
}

resource "aws_lb_target_group_attachment" "tg-attachment" {
  for_each = var.port_forwarding_config
    target_group_arn = "${aws_lb_target_group.tg[each.key].arn}"
    port = each.key
    target_id = "${aws_instance.instance[1].id}"
}```
````

---

<div class="post-metadata">

**Author:** ![maxb](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/maxb/32/26655_2.png) [@maxb](https://discuss.hashicorp.com/u/maxb)\
**Post date:** [April 22, 2022, 10:06am UTC](https://discuss.hashicorp.com/t/multiple-iteration-in-one-resource/38612/2 "2022-04-22T10:06:28Z")

</div>

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:

```auto
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.)
