Vijay Gupta
Vijay Gupta

Reputation: 47

How to add Multiple Data Disk to Multiple Azure VM's using Terraform

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
  }
 
  }

Upvotes: 0

Views: 1776

Answers (1)

Marcin
Marcin

Reputation: 238957

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" 
  }
}

Upvotes: 1

Related Questions