如何在 Terraform 中使用 Loops 来部署 2 个不同的 azure 资源

how to use Loops in Terraform to deploy 2 different azure resources

我目前正在编写一些部署 Azure Datalake Gen2 存储文件系统和每个文件系统的文件夹结构的 Terraform 代码。

在创建变量列表中声明的所有文件系统时,以下代码工作正常。

variable.tf

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

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

main.tf

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"
  }
}

现在我想为上面创建的每个产品文件系统创建一个通用的子文件夹结构。

当我一次传递一个文件系统来创建文件夹结构时,以上代码有效。

我想遍历这两个变量并创建如下所示的文件夹结构。

您可以使用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"
  }
}