簡體   English   中英

如何使用 Terraform 中的循環來部署 2 個不同的 azure 資源

[英]how to use Loops in Terraform to deploy 2 different azure resources

我目前正在編寫一些 Terraform 代碼,為每個文件系統部署 Azure Datalake Gen2 存儲文件系統和文件夾結構。

創建變量列表中聲明的所有文件系統時,下面的代碼工作正常。

變量.tf

variable "product_unified_filesystem" {
   default =  [
     "product1",
     "product2",
     "product3"
     ]
}

variable "product_unified_subdirs" {
  default = [
    "subdirectory1",
    "subdirectory2",
    "subdirectory3"
  ]
}

主程序

resource "azurerm_storage_data_lake_gen2_filesystem" "unified-filesystem" {
  count              = length(var.product_unified_filesystem)
  name               = var.product_unified_filesystem[count.index] 
  storage_account_id = module.storage.id
}

resource "azurerm_storage_data_lake_gen2_path" "unified-subdirs-1" {
  count              = length(var.product_unified_subdirs)
  path               = var.product_unified_subdirs[count.index]  
  filesystem_name    = "product1"
  storage_account_id = module.storage.id
  resource           = "directory"
  }
}
resource "azurerm_storage_data_lake_gen2_path" "unified-subdirs-2" {
  count              = length(var.product_unified_subdirs)
  path               = var.product_unified_subdirs[count.index]  
  filesystem_name    = "product2"
  storage_account_id = module.storage.id
  resource           = "directory"
  }
}

resource "azurerm_storage_data_lake_gen2_path" "unified-subdirs-3" {
  count              = length(var.product_unified_subdirs)
  path               = var.product_unified_subdirs[count.index]  
  filesystem_name    = "product3"
  storage_account_id = module.storage.id
  resource           = "directory"
  }
}

現在我想為上面創建的每個產品文件系統創建一個通用的子文件夾結構。

當我一次通過一個文件系統來創建文件夾結構時,上面的代碼有效。

我想遍歷這兩個變量並創建一個文件夾結構,如下所示。

  • 產品1 子目錄1 子目錄2 子目錄3
  • 產品 2 子目錄 1 子目錄 2 子目錄 3
  • 產品 3 子目錄 1 子目錄 2 子目錄 3

您可以使用setproduct獲取所有組合。 此外,最好使用for_each而不是count ,因為它不依賴於項目的排序。

locals {
  fs_subdir = {
    for val in setproduct(var.product_unified_filesystem, var.product_unified_subdirs):
      "${val[0]}-${val[1]}" => {
        product = val[0]
        subdir = val[1]
      }
  }
}

然后


resource "azurerm_storage_data_lake_gen2_filesystem" "unified-filesystem" {
  for_each           = toset(var.product_unified_filesystem)
  name               = each.key
  storage_account_id = module.storage.id
}

resource "azurerm_storage_data_lake_gen2_path" "unified-subdirs" {
  for_each           = local.fs_subdir
  path               = each.value.subdir
  filesystem_name    = each.value.product
  storage_account_id = module.storage.id
  resource           = "directory"
  }
}

暫無
暫無

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

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