Terraform兼容性错误-未使用count.index

时间:2019-09-14 13:49:16

标签: terraform terraform-provider-azure

我使用的是0.12 Terraform,脚本是用0.11 Terraform编写的。

代码块为:

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

尝试运行Terraform脚本时出现错误

错误:

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]

如何更改以摆脱此错误?

2 个答案:

答案 0 :(得分:0)

由于您使用计数定义了资源azurerm_availability_set.name_av_set,因此现在将其视为对象列表。 因此,您不能在azurerm_virtual_machine.name_av_set中设置azurerm_availability_set.name_av_set.id,它必须是azurerm_availability_set.name_av_set.0.id或建立索引。

答案 1 :(得分:0)

根据错误消息中的建议,您可以将[count.index]部分添加到引用中,只要这两个资源都具有count = var.node_count

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

如果您遵循the documented upgrade process,则terraform 0.12upgrade工具可以自动处理这种重写。在这种情况下,升级工具会选择其他解决方案,因为它是比较保守的选择:

  availability_set_id = azurerm_availability_set.name_av_set[0].id

硬编码索引0更适合表达式的Terraform 0.11行为,因为在Terraform 0.11中,azurerm_availability_set.name_av_set.id意味着采用{{1 }}。

要选择哪些选项取决于您是要始终选择第一个可用性集,还是要将每个虚拟机与另一个可用性集相关联。