Access parent resource configuration with dynamic for_each

I’m trying to migrate our azurerm_managed_disk and azurerm_virtual_machine_data_disk_attachment resources to use the storage_os_disk block in azurerm_virtual_machine using dynamic for_each.

The virtual machine block is using count, prepending the name of the VM to the disks used to be done with count.index. How would I access the name of the VM when creating the disks using for_each? We need the name of the VM (the parent resource) to be prepended to the disk name

  dynamic "storage_data_disk" {
    for_each = local.data_disks
    content {
      name                      = "${VM_NAME_HERE}.storage_data_disk.value.name}"
      create_option             = "Empty"
      lun                       = storage_data_disk.value.lun
      disk_size_gb              = storage_data_disk.value.size
      managed_disk_type         = "Premium_LRS"
      caching                   = storage_data_disk.value.caching
      write_accelerator_enabled = storage_data_disk.value.write_accel
    }
  }

The data disk list is similar to this:

data_disks = [
  {
    name = "data1"
    size = 20
    lun = 0
    caching = "None"
    write_accel = "false"
  },
  {
    name = "data2"
    size = 20
    lun = 1
    caching = "None"
    write_accel = "false"
  },
  {
    name = "data3"
    size = 20
    lun = 2
    caching = "None"
    write_accel = "false"
  }
]

I am facing same issue, can some one help me ?

To make sure I understand: you’re creating multiple VMs with count, and then for each VM, you’re creating multiple data_storage_disk sub-resources with a dynamic block? So you’ll have (VM count) * (disk count) disks?

I think you should still be able to use count.index within those dynamic blocks, and it should still refer to the parent resource. Unless you also switched to using the resource-level for_each instead of count, in which case you’d need the each object.