Search code examples
terraformterraform-provider-azure

Azure linux virtual machine terraform map variable issue


I am using the below terraform script values for my azurerm_linux_virtual_machine terraform script but getting below error:

"The given value is not suitable for var.vm_properties declared at variables.tf:147,1-25: element "os_disk": attributes "os_disk" and "source_image" are required.

I have tried all the possible changes I could think of but it is not working. I am not able to understand what am I missing here

main.tf file entry:

  os_disk {
    name                 = var.vm_properties["os_disk"]["name"]
    caching              = var.vm_properties["os_disk"]["caching"]
    storage_account_type = var.vm_properties["os_disk"]["storage_account_type"]
  }

  source_image_reference {
    publisher = var.vm_properties["source_image"]["publisher"]
    offer     = var.vm_properties["source_image"]["offer"]
    sku       = var.vm_properties["source_image"]["sku"]
    version   = var.vm_properties["source_image"]["version"]
  }

variables.tf file entry :

variable "vm_properties" {
  type = map(object({
    os_disk = object({
      name                 = string
      caching              = string
      storage_account_type = string
    })
    source_image = object({
      publisher = string
      offer     = string
      sku       = string
      version   = string
    })
  }))
}

terraform.tfvars file entry:

vm_properties = {
  os_disk = {
    name                 = "myOsDisk"
    caching              = "ReadWrite"
    storage_account_type = "Premium_LRS"
  }
  source_image = {
    publisher = "Canonical"
    offer     = "UbuntuServer"
    sku       = "18.04-LTS"
    version   = "latest"
  }
}

Solution

  • Since you have defined your variable as a map(object...), it will require a key as well, e.g.:

    vm_properties = {
      "somekeyvalue" = {
        os_disk = {
          caching              = "value"
          name                 = "value"
          storage_account_type = "value"
        }
        source_image = {
          offer     = "value"
          publisher = "value"
          sku       = "value"
          version   = "value"
        }
      }
    }
    

    To fix this, you can define your variable as object(...):

    variable "vm_properties" {
      type = object({
        os_disk = object({
          name                 = string
          caching              = string
          storage_account_type = string
        })
        source_image = object({
          publisher = string
          offer     = string
          sku       = string
          version   = string
        })
      })
    }
    

    The value you have assigned to the variable will then be valid.