【问题标题】:Referencing outputs from a for_each module引用来自 for_each 模块的输出
【发布时间】:2021-01-15 16:23:00
【问题描述】:

我有一个模块,它有一个使用 for_each 定义的变量,它的输出如下:

output "nic_ids" {
    value = [for x in azurerm_network_interface.nic : x.id]
}
nic_ids = [
  "/subscriptions/*****/resourceGroups/test-rg/providers/Microsoft.Network/networkInterfaces/test-nic-1",
  "/subscriptions/*****/resourceGroups/test-rg/providers/Microsoft.Network/networkInterfaces/test-nic-2",
]

我的目标是将以上 NIC id 传递给 VM 模块,并在 NIC id 和 VM 之间进行 1:1 映射(test-nic-1 应该只附加到 vm-1 test-nic-2vm-2 等)

module "vm" {
  source  = "*****/vm/azurerm"
  version = "0.1.0"
  
   vms = var.vms
   nic_ids = module.nic[each.value.id].nic_ids 
} 

我遇到以下错误:

Error: each.value cannot be used in this context

  on main.tf line 58, in module "vm":
  58:    nic_ids = module.nic[each.value.id].nic_ids 

A reference to "each.value" has been used in a context in which it
unavailable, such as when the configuration no longer contains the value in
its "for_each" expression. Remove this reference to each.value in your
configuration to work around this error.

我用这个similar question 作为参考。 你能推荐一下吗?

【问题讨论】:

    标签: terraform terraform-provider-azure


    【解决方案1】:

    您可以将上述 NIC id 列表传递给带有 count 的 VM 模块。

    module "vm" {
      source              = "./modules/vms"
      vm_names            = ["aaa","bbb"]
    
      nic_ids = module.nic.network_interface_nics  
    }
    
    module "nic" {
      source = "./modules/nic"
    
      nic_names = ["nic1","nic2"]
    
    }
    

    VM 模块中的main.tf

    resource "azurerm_virtual_machine" "vm-windows" {
      count                         = length(var.vm_names)
      name                          = var.vm_names[count.index]
      resource_group_name           = data.azurerm_resource_group.vm.name
      location                      = var.location
      vm_size                       = var.vm_size
      network_interface_ids         = [ var.nic_ids[count.index] ]
    ...
    
    }
    

    网卡模块中的output.tf

    output "network_interface_nics" {
      description = "ids of the vm nics provisoned."
      value       = [for x in azurerm_network_interface.nic : x.id]
    }
    

    【讨论】:

    • 谢谢南希,是的,这是一种方法。我更喜欢使用 for_each 来避免使用 count 带来的索引问题。
    猜你喜欢
    • 2021-08-26
    • 2021-03-07
    • 2021-03-21
    • 2021-04-20
    • 2021-03-31
    • 2021-11-19
    • 2021-04-18
    • 2021-08-16
    • 2021-09-24
    相关资源
    最近更新 更多