簡體   English   中英

Terraform:在模塊中使用 for_each

[英]Terraform : Using for_each in module

我正在使用 terraform 版本 0.14.3。 我有一個用於創建 Azure 網絡接口卡的模塊,如下所示:

resource "azurerm_network_interface" "nic" {

  name                = var.nic_name
  location            = var.location
  resource_group_name = var.rg_name

  ip_configuration {
    name                          = var.ipconfig_name
    subnet_id                     = var.subnet_id
    private_ip_address_allocation = "Dynamic"
  }
}

其output定義為:

output "nic_id" {
     value = azurerm_network_interface.nic.id 
}

我在這個父模塊中調用這個模塊:

module "NIC" {
  source = "./NIC"
  for_each = var.nics

  nic_name      = each.value.nic_name
  location      = "eastus2"
  rg_name       = "abc-test-rg"
  ipconfig_name = each.value.ipconfig_name
  subnet_id     = <subnet_id>
}

output "nic_ids" {
  value = [for k in module.NIC.nic_id : k.id]
} 

NIC 值定義如下:

nics = {
  nic1 = {
    nic_name      = "abc-nic-1"
    ipconfig_name = "nic-1-ipconfig"
  }
}

我想循環 NIC output ID,並希望它們顯示。 當我運行上面的代碼時,在terraform 計划中出現以下錯誤:

Error: Unsupported attribute

  on main.tf line 15, in output "nic_ids":
  15:   value = [for k in module.NIC.nic_id : k.id]
    |----------------
    | module.NIC is object with 1 attribute "nic1"

This object does not have an attribute named "nic_id".

我該如何解決?

Your module "NIC" block has for_each set, and so the module.NIC symbol elsewhere in the module is a mapping from instance keys to output objects, rather than just a single output object as for a singleton module.

Terraform 的錯誤消息試圖通過以下消息引起人們的注意:

  • module.NIC is object with 1 attribute "nic1"

請注意,此處的nic1是來自您的var.nics的鍵,而不是模塊中定義的 output 值之一。

假設您在此處顯示的nic_id output 是該模塊中唯一定義的,那么module.NIC值的形狀將如下所示:

{
  nic1 = {
    nic_id = "eni-e5aa89a3"
  }
}

聽起來你想產生一個像這樣的值:

{
  nic1 = "eni-e5aa89a3"
}

如果是這樣,獲得該結果的合適表達式如下:

output "nic_ids" {
  value = { for k, nic in module.NIC : k => nic.nic_id }
} 

上面的意思是:為NIC模塊的每個實例生成一個映射,其鍵為模塊實例鍵,其值為nic_id output 值。

或者,如果哪個 id 屬於哪個實例並不重要,那么您可以生成一組無序的 id,如下所示:

output "nic_ids" {
  value = toset([for nic in module.NIC : nic.nic_id])
} 

在這種情況下, for表達式只定義了一個本地符號nic ,它表示模塊實例 object,因為它對實例鍵沒有任何作用。 這里的toset表示 ID 沒有任何特定的順序:這不是絕對必要的,但我認為確保任何其他 Terraform 代碼取決於該值不會無意中依賴於當前任意id 的順序,如果您在var.nics中添加或刪除元素,將來可能會改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM