azure Terraform -在调用中使用for_each时从模块输出中检索特定属性

8ehkhllq  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(134)

我想知道是否有可能从模块输出中选择一个特定的属性,因为我知道我调用模块时使用的是循环。
1.在Map上使用for_each调用backup_policy模块
1.将创建策略并在模块输出中提供其ID
1.调用VM模块并在调用中指定VM必须与之链接的策略ID
下面是代码示例:
调用backup_policy模块:

locals {
  backup_policies = {
    "daily-critical" = {
    ...
    }
    "daily-qa" = {
    ...
    }
  }
}

module "backup_policy" {
  source = "path/to/my/module"

  for_each = local.backup_policies

  location            = local.location
  resource_group_name = module.rg.resource_group_name

  vm_backup_policy_name = "${each.key}-backup-policy"
}

备份策略模块代码:

resource "azurerm_backup_policy_vm" "vm_backup_policy" {
  name                = var.vm_backup_policy_name
  resource_group_name = var.resource_group_name
  recovery_vault_name = var.recovery_vault_name
  ....
  }

backup_policy模块输出代码:

output "vm_backup_policy_id" {
  value       = azurerm_backup_policy_vm.vm_backup_policy.id
}

现在我的策略已经创建好了,我想使用策略ID将它们链接到虚拟机。但是我想使用策略名称指定哪个策略必须链接到哪个虚拟机。大致如下所示(请看最后一行):

locals {
  location = "East US"

  vms = {
    "my-vm1" = {
      size          = "Standard_DS12_v2"
      backup_policy = "daily-critical"
    }
    "my-vm2" = {
      size          = "Standard_DS12_v2"
      backup_policy = "daily-qa"
    }
  }
}

module "vms" {
  source = "path/to/my/module"

  for_each            = local.vms
  vm_name             = each.key
  location            = local.location
  resource_group_name = module.rg.resource_group_name

  backup_policy_id = module.backup_policy.vm_backup_policy_id[each.value["backup_policy"]]
}

是否可以或者必须向backup_policy模块发送一个名称列表,并在模块端执行for_each,以便在输出中生成Map?

t98cgbkg

t98cgbkg1#

有两种方法可以用来解决这类问题(例如,您有两个单独的、但相关的资源/模块,您希望使用for_each创建它们)。
第一个基本上就是你所要问的问题,为此你只需要修改代码中的一行。

backup_policy_id = module.backup_policy.vm_backup_policy_id[each.value["backup_policy"]]

应该是

backup_policy_id = module.backup_policy[each.value["backup_policy"]].vm_backup_policy_id

我倾向于采用的另一种方法是将这些依赖的资源/模块组合成一个单独的模块,然后一起创建它们。例如:

# ./modules/my-combined-module/main.tf

variable "location" {}
variable "resource_group_name" {}
variable "vm_backup_policy_name" {}
variable "vm_name" {}

module "backup_policy" {
  source                = "../ba"
  location              = var.location
  resource_group_name   = var.resource_group_name
  vm_backup_policy_name = "${each.key}-backup-policy"
}

module "vms" {
  source = "../vm"

  vm_name             = var.vm_name
  location            = var.location
  resource_group_name = var.resource_group_name
  backup_policy_id    = module.backup_policy.vm_backup_policy_id
}

然后就跑

module "my_combined_module" {
  source   = "./modules/my-combined-module"
  for_each = local.vms

  vm_name               = each.key
  vm_backup_policy_name = each.value["backup_policy"]
  location              = local.location
  resource_group_name   = local.resource_group_name
}

相关问题