azureterraformterraform-provider-azure

Terraform: Use count.index in variable name


Is it possible to use count.index in a variable name, so I can use a single map variable for multiple resources? For example

variables.tf:

variable "disk_share_sizes" {
  type        = map(number)
  description = "Sizes for VM Disks and File Shares"
  default = {
    fileshare   = 2048
    pvs0        = 20
    pvs1        = 10
    cca0        = 50
    cca1        = 80
  }
}

compute.tf

resource "azurerm_managed_disk" "vm_pvs" {
  count                = 2
  name                 = "pvs-disk-${format("%02d", count.index + 1)}"
  location             = "useast"
  resource_group_name  = "MyRGName"
  storage_account_type = "MyStorAccount"
  create_option        = "Empty"
  disk_size_gb         = var.vm_disk_sizes.pvs[count.index]
}

resource "azurerm_managed_disk" "vm_cca" {
  count                = 2
  name                 = "cca-disk-${format("%02d", count.index + 1)}"
  location             = "useast"
  resource_group_name  = "MyRGName"
  storage_account_type = "MyStorAccount"
  create_option        = "Empty"
  disk_size_gb         = var.vm_disk_sizes.cca[count.index]
}

This produces the below error (repeated for both resources):

│ Error: Invalid index
│
│   on compute.tf line 8, in resource "azurerm_managed_disk" "my_vms":
│  8:   disk_size_gb         = var.vm_disk_sizes.vm[count.index]
│     ├────────────────
│     │ count.index is a number
│     │ var.vm_disk_sizes.vm is a number
│
│ This value does not have any indices.

I can't use "var.vm_disk_sizes.vm${count.index}" as this is a variable name and putting it in double quotes will just make it a string. I did try using ${var.vm_disk_sizes.vm${count.index}} but it doesn't like this either

Can this be done without making the variable a list rather than a map? I'm using a map as my actual map is larger, and it would be difficult to split this into multiple lists for all the different VMs and disk sizes.


Solution

  • Ideally, you would use the for_each meta-argument instead (since your variable is defined as a map):

    resource "azurerm_managed_disk" "my_vms" {
      for_each             = var.vm_disk_sizes
      name                 = "vm-disk-${each.key}"
      location             = "useast"
      resource_group_name  = "MyRGName"
      storage_account_type = "MyStorAccount"
      create_option        = "Empty"
      disk_size_gb         = each.value
    }