How do I create N VMs with M disks created and attached per VM?

China☆狼群 提交于 2021-01-28 08:34:08

问题


resource "azurerm_windows_virtual_machine" "virtual_machine" { 
    count = var.vm_count 
    name  = "${local.vm_name}${count.index +1}"

resource "azurerm_virtual_machine_data_disk_attachment" "datadisk01" {
    count              = var.disk_count  
    **virtual_machine_id = azurerm_windows_virtual_machine.virtual_machine[count.index].id
    managed_disk_id    = element("${module.DISK.datadisk_id}","${count.index}")

}

Issue - I have 2 diffenent count varaibles vm_count and disk_count. I want a generic solution, Ex. If vm count is 2 and each VM should have 3 datadisk i.e. disk_count is 3.

I am able to create multiple VMs and Disks as per the count. But facing issue while vm and disk attachment, as i am not able to use 2 counts in same resource. How to handle this situation?

facing issue on the line maked as**

In summary, I want to create vm_count (N) VMs, with disk_count (M) disks created and attached to each VM.

How do I create N VMs with M disks created and attached per VM?


回答1:


You can achieve something like this using a set of indexes:

locals {

  indexes = {
    for vmi in range(var.vm_count): vmi => [
      for ddi in range(var.disk_count):
        ddi
    ]
  }

}

Which will create a map like this:

{
  "0" = [
    0,
    1,
    2,
  ]
  "1" = [
    0,
    1,
    2,
  ]
}

For later usage in this way:

resource "azurerm_virtual_machine_data_disk_attachment" "datadisk01" {
    for_each = local.indexes

    virtual_machine_id = azurerm_windows_virtual_machine.virtual_machine[tonumber(each.key)].id
    managed_disk_id    = element("${module.DISK.datadisk_id}","${each.value[0]}")
}

I haven't fully tested the output as the VM needs more configuration. However as I can see you are using locals for vm_name I would create a map/object with VM names containing the index, the values and the desired disks.

I hope this help resolve the issue.




回答2:


The only way i've been able to have 2 loops in a resource is using a dynamic block.

Something like this:

resource "azurerm_windows_virtual_machine" "virtual_machine" { 
    count = var.vm_count 
    name  = "${local.vm_name}${count.index +1}"

    dynamic "setting" {
     for_each = var.disk_count
     content {
        ##Storage_disk block
     }
   }

You can then access the index with each.value if required.



来源:https://stackoverflow.com/questions/63776587/how-do-i-create-n-vms-with-m-disks-created-and-attached-per-vm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!