Terraform v0.13+:在模块中使用计数

时间:2021-01-06 17:52:21

标签: terraform terraform-provider-azure

我使用的是 Terraform 版本 v0.14.3。 我在模块中使用 count 来创建多个相同类型的 Azure 资源(网络接口卡、VM)。 下面是父模块,调用子模块 NICVM :

module "NIC" {
  source = "./NIC"
  count  = 2

  nic_name      =  "vm-nic-${count.index + 1}" 
  nic_location  = "eastus2"
  rg_name       = "abc-test-rg"
  ipconfig_name = "vm-nic-ipconfig-${count.index + 1}" 
  subnet_id     = "/subscriptions/***********/resourceGroups/abc-test-rg/providers/Microsoft.Network/virtualNetworks/abc-test-vnet/subnets/abc-test-vnet"
  
}
output "nic_id" {
  value = module.NIC[*].nic_id
}
module "VM" {
  source = "./VM"
  count = 2

  vm_name        = "test-vm"
  rg_name        = "abc-test-rg"
  location       = "eastus2"
  admin_password = var.admin_password
  nic_id         = [module.NIC[*].nic_id]
  
}

我在 terraform plan 中遇到以下错误:

Error: Incorrect attribute value type

  on VM\main.tf line 8, in resource "azurerm_linux_virtual_machine" "vm":
   8:   network_interface_ids           = var.nic_id
    |----------------
    | var.nic_id is tuple with 1 element

Inappropriate value for attribute "network_interface_ids": element 0: string
required.

如何循环生成的两个 NIC id 并将它们传递给 VM 模块中的两个 VM? 提前致谢!

1 个答案:

答案 0 :(得分:2)

使用 count.index 引用与您在第二个模块调用中配置的 VM 数量相关的输出的特定值。

  nic_id         = [module.NIC[count.index].nic_id]