Search code examples
for-loopvariablesforeachterraform

Iterating through values of a two variables


I'm using terraform alb community module to assign IPs to subnets. I managed to do it in three seprate sets (as below). Is there a way to do it one bracket using for or for_each loop? Thanks!

    subnet_mapping =  [
    {
      allocation_id = var.allocation_id[0]
      subnet_id = var.public_subnets[0]
    },
    {
      allocation_id = var.allocation_id[1]
      subnet_id = var.public_subnets[1]
    },
    {
      allocation_id = var.allocation_id[2]
      subnet_id = var.public_subnets[2]
    }
    ]

variables.tf

variable "public_subnets" {
 type        = list(string)
 description = "Public Subnet ids"
 default     = ["subnet-0b11fb63b479xxxx", "subnet-0f401893ad414xxx", "subnet-0887c57b023fxxx"]
}
variable "allocation_id" {
    type = list(string)
    description = "List of allocation ids of elastic IPs"
    default = ["eipalloc-058fa2edc336f1xxx","eipalloc-012227feb7cf9xxx","eipalloc-075bf28dc2b5cxxx"]
}

Solution

  • Essentially the same answer as https://stackoverflow.com/a/77565922 except for the type definition listing each single attribute

    variable "subnet_mapping" {
      type = list(object({
                allocation_id = string
                subnet_id     = string
              }))
      default = [
                 {allocation_id = "x1", subnet_id = "y1"},
                 {allocation_id = "x2", subnet_id = "y2"},
                 {allocation_id = "x3", subnet_id = "y3"}
                ]
    }
    
    
    output "subnet_mapping" {
      value = var.subnet_mapping
    }
    

    Running terraform apply yields:

    subnet_mapping = tolist([
      {
        "allocation_id" = "x1"
        "subnet_id" = "y1"
      },
      {
        "allocation_id" = "x2"
        "subnet_id" = "y2"
      },
      {
        "allocation_id" = "x3"
        "subnet_id" = "y3"
      },
    ])
    

    In any event, creating one variable (list of objects) instead of two lists makes sense because it reduces the possibility of errors.