terraformpackerhashicorphashicorp-packer

Reference the iteration number in a Hashicorp Packer for_each loop


consider the following HCL Map:

locals {
  disks = {
    sda = {
      size = 1024
      thin = true
    }
    sdb = {
      size = 2048
      thin = false
    }
  }
}

and the following source "vsphere-iso" "linux-rhel" dynamic storage block:

  dynamic "storage" {
    for_each = local.disks
    content {
      disk_size             = storage.value.size
      disk_thin_provisioned = storage.value.thin
      disk_controller_index = ???
    }
  }

What value can I substitute ??? for that will increment with each iteration? I know count.index works with a count=XX loop, but would like to not have to add the index value to the the map, since it's just calculated anyway.


Solution

  • One way would be to add index to local.disks:

    locals {
      disks = {
        sda = {
          size = 1024
          thin = true
          index = 0
        }
        sdb = {
          size = 2048
          thin = false
          index = 1
        }
      }
    }
    

    Alternatively iterate over keys:

     dynamic "storage" {
        for_each = keys(local.disks)
        content {
          disk_size             = local.disks[storage.value].size
          disk_thin_provisioned = local.disks[storage.value].thin
          disk_controller_index = storage.key # key will be index number
        }
      }
    

    but the storage.key will not necessarily represent apparent order as in local.disks, because maps do not have order.