繁体   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