'How to use `for_each` on resource attribute blocks in Terraform?

I'm attempting to create multiple route rules in OCI, for a single route table. However, the for_each meta-argument only works on resources themselves, not related attributes. Psuedo-code example:

resource "oci_core_route_table" "example-rt" {
  compartment_id = oci_identity_compartment.example-compartment.id
  vcn_id         = oci_core_vcn.example-vcn.id

  route_rules {

    for_each = {
      # Route dest CIDR
      dest1      = var.dest1-cidr
      dest2      = var.dest2-cidr
      dest3      = var.dest3-cidr
    }

    network_entity_id = oci_core_internet_gateway.example-igw.id
    destination = each.value
    destination_type = "CIDR_BLOCK"
  }

I can obviously point and click in OCI to create these rules, but I'm hoping this can be accomplished with Terraform.

Thanks.



Solution 1:[1]

You can use a dynamic block:

resource "oci_core_route_table" "example-rt" {
  compartment_id = oci_identity_compartment.example-compartment.id
  vcn_id         = oci_core_vcn.example-vcn.id

  dynamic "route_rules" {
    for_each = toset([var.dest1-cidr, var.dest2-cidr, var.dest3-cidr])

    content {
      network_entity_id = oci_core_internet_gateway.example-igw.id
      destination = route_rules.key
      destination_type = "CIDR_BLOCK"
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1