Terraform wants to replace dynamically attached data disks on azurerm

Hi guys im currently try to create dynamically data disk for some virtual machines. The creation of data disk. For exemple : I want to create 2 VM with 3 data disks
so the expected result for the name of data disks is :
DD01-VM-1
DD02-VM-1
DD03-VM-1
DD01-VM-2
DD02-VM-2
DD03-VM-2
I use the following code :

Creation of data disks

resource "azurerm_managed_disk" "MyDataDiskVm" {
  count                = "${var.nb_data_disk * var.nb_vms}"
  name = "${format("DD%02d", (count.index % var.nb_data_disk) +1)}-VM-${var.vm_name_suffix}${format("%d", floor((count.index / var.nb_data_disk) +1))}"
  location             = "${var.location}"
  resource_group_name  = "${var.resource_group_name}"
  storage_account_type = "Standard_LRS"
  disk_size_gb         = "${var.data_disk_size_gb}"
  create_option        = "Empty"
  depends_on = ["azurerm_virtual_machine.MyVms"]
}

Attach the created data disk to viritual machine

resource "azurerm_virtual_machine_data_disk_attachment" "MyDataDiskVmAttach" {
  count              = "${var.nb_data_disk * var.nb_vms}"
  managed_disk_id    = "${azurerm_managed_disk.MyDataDiskVm.*.id[count.index]}"
  virtual_machine_id = "${azurerm_virtual_machine.MyVms.*.id[ceil((count.index +1) * 1.0 / var.nb_data_disk) -1]}"
  lun                = "${count.index % var.nb_data_disk}"
  caching            = "ReadWrite"
  create_option      = "Attach"
  depends_on         = ["azurerm_managed_disk.MyDataDiskVm"]
}

Everything works fine, datadisks are created with the right name is correctly attached to vm but once i restart an “apply” Terraform wants to change the id of the datadisks and therefore destroy and recreate it…

-/+ azurerm_managed_disk.MyDataDiskVm[0] (new resource required)

Im using Terraform v0.11.11.

Do you know where the error may come from or is it possible to dynamically create data disks with an “for each” with the azurerm provider ?

Thx for your feedback

1 Like

Hi @Hatsou,
Am also same situation with google cloud provider, did you got any solution for this ?
Terraform version: 0.12.10
resource “google_compute_disk” “node” {
count = (var.add_disk == true ? var.vm * var.disks : 0)
project = var.project
name = format("%s%02d-disk", var.add_disk_name, count.index + 1)
zone = element(var.zones, count.index%length(var.zones))
size = var.data_disk_size
type = var.disk_type
labels = {
business_unit = var.label
}
}