1
votes

I am using 0.12 Terraform, and the script was written in 0.11 Terraform.

Code block is:

resource "azurerm_virtual_machine" "name_av_set" {
  count               = "${var.node_count}"
  #count               = "$length(var.node_count)"
  name                = "${var.resource_name_prefix}-pool-${var.name}-${format("%03d", count.index + 1)}-vm"

  availability_set_id = "${azurerm_availability_set.name_av_set.id}"

When trying to run Terraform script , getting error

Error:

Error: Missing resource instance key

  on main.tf, in resource "azurerm_virtual_machine" 
  58:   availability_set_id = "${azurerm_availability_set.name_av_set.id}"

Because azurerm_availability_set.name_av_set has "count" set, its
attributes must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use:
    azurerm_availability_set.name_av_set[count.index]

How to change to get rid of this error?

2
This error would also have been thrown on 0.11 Terraform.Matt Schuchard

2 Answers

2
votes

As suggested in the error message, you can add the [count.index] part to your reference, as long as both of these resources have count = var.node_count:

  availability_set_id = azurerm_availability_set.name_av_set[count.index].id

If you follow the documented upgrade process then the terraform 0.12upgrade tool can handle this sort of rewriting automatically. The upgrade tool would choose a different solution in this case because it is the more conservative choice:

  availability_set_id = azurerm_availability_set.name_av_set[0].id

Hard-coding index 0 is a better match for the Terraform 0.11 behavior of your expression because in Terraform 0.11 azurerm_availability_set.name_av_set.id means to take the id of the first instance of azurerm_availability_set.name_av_set.

Which of these to choose depends on whether you intend to always select the first availability set or whether you want to correlate each virtual machine with a different availability set.

0
votes

Because you defined the resource azurerm_availability_set.name_av_set with a count, it's now treated as a list of objects. So you cant set azurerm_availability_set.name_av_set.id in azurerm_virtual_machine.name_av_set it needs to be azurerm_availability_set.name_av_set.0.id or indexed.