0

How can i add Multiple Data to multiple azure VM's. I am creating VMs using MAP with For_each so Count can not be used . Below is my VM Code .

So all the VMs have 2 data disks with 120 GB size.

disk_count = 2
disk_size = 120

    vm_names = {
    testvm = "10.0.1.5",
    testvm2 = "10.0.1.6"

}

    resource "azurerm_virtual_machine" "terraform_windows" {
    for_each =                        var.vm_names
    name                           =  each.key
    location                       =  var.location
    resource_group_name            =  data.azurerm_resource_group.Resource_group.name
    network_interface_ids          =  ["${azurerm_network_interface.az_nic[each.key].id}"]
    vm_size                        =  var.vm_size
    delete_os_disk_on_termination  =   true
    delete_data_disks_on_termination = true

    storage_image_reference {
    publisher = var.OS_win["publisher"]
    offer     = var.OS_win["offer"]
    sku       = var.OS_win["sku"]
    version   = "latest"
  }

    storage_os_disk {
    name              = "${each.key}_OSdisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = var.hdd_type
    os_type           = var.os_type
    disk_size_gb = "127" 
  }

    os_profile {
    computer_name  = each.key
    admin_username = "azureadmin"
    admin_password = "Azurecloud@321$%"
  }

    os_profile_windows_config {
    enable_automatic_upgrades = true
    provision_vm_agent = true
  }
 
  }
2
  • 1
    What's wrong with the current code? Any errors? Commented Feb 24, 2022 at 10:11
  • i want to create and attach data disk to vm for that i am not getting code means how can i use for_each to create and attach data disk to VM Commented Feb 24, 2022 at 10:13

1 Answer 1

1

You can use dynamic blocks:

 dynamic "storage_os_disk" {

    for_each = range(var.disk_count)

    content {
      name              = "${storage_os_disk.key}_OSdisk"
      caching           = "ReadWrite"
      create_option     = "FromImage"
      managed_disk_type = var.hdd_type
      os_type           = var.os_type
      disk_size_gb = "127" 
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

in this case Os & Data Disk will hv same size. can be use azurerm_managed_disk" & "azurerm_virtual_machine_data_disk_attachment"
@VijayGupta You're code does not have such resources.
that what i need if you could give me , unable to put logic
@VijayGupta It would be better to make new question with the code you tried yourself on how to do it. My answer addresses your current code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.