Terraform | “count” 对象只能在 “resource” 和 “data” 块中使用

81次阅读
没有评论

问题描述

在升级 Terraform 到最新版本 0.12 时遇到了问题。在某对资源块中,当尝试执行 terraform plan 命令时,出现以下错误信息:

The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set.

用户已经尝试移除 count 索引,但出现了另一个错误,提示需要 count 索引。以下是用户提供的 Terraform 配置的关键部分:

resource "azurerm_network_interface" "network_interface" {
  count    = "${var.vm_server_count}"
  location = "${var.location}"
}

resource "azurerm_network_interface_backend_address_pool_association" "network_interface" {
  network_interface_id    = "${azurerm_network_interface.network_interface[count.index]}"
  ip_configuration_name   = "example"
  backend_address_pool_id = "${azurerm_lb_backend_address_pool.network_interface.id}"
}

请问我在这里漏掉了什么?这是使用 Azure 作为提供商的 Terraform 0.12 稳定版。

解决方案

请注意以下操作注意版本差异及修改前做好备份。
根据用户提供的 Terraform 配置和最佳回答,以下是解决方案的步骤:

  1. azurerm_network_interface_backend_address_pool_association 资源块中,没有设置 count 参数,因此在该块中使用 count.index 是没有意义的。
  2. 根据你使用的资源类型,我猜测你的意图是为每个网络接口创建一个关联。如果是这样,你需要在第二个资源块中添加以下 count 参数:
    hcl
    count = length(azurerm_network_interface.network_interface)

    这样做可以确保为每个网络接口创建一个 azurerm_network_interface_backend_address_pool_association

    注意:在 Terraform 0.11 中,这样做不会报错,但它不会按照你的意图工作:它只会为第一个网络接口创建一个 azurerm_network_interface_backend_address_pool_association,其他的网络接口将保持未关联状态。

  3. 如果你的意图只是关联第一个网络接口,那么你可以将第二个资源块中的 count.index 替换为 0,明确地表示它只使用第一个网络接口:
    hcl
    network_interface_id = azurerm_network_interface.network_interface[0]

这样,根据你的意图,你可以根据上述步骤修改 Terraform 配置。

正文完