首页 > 解决方案 > 具有嵌套列表的 Terraform 动态块

问题描述

我需要使用 Terraform 在 Pagerduty 中创建升级策略。我想动态创建rule块,然后在其中target块中的值来自rule. 我不确定如何在目标块内进行第二次调用以使其动态化。我有一个列表中的团队列表。

locals {
  teams = [
    [data.pagerduty_schedule.ce_ooh_schedule.id, data.pagerduty_schedule.pi_office_hours_schedule.id],
    [data.pagerduty_schedule.delivery_managers_schedule.id]
  ]
}

resource "pagerduty_escalation_policy" "policy" {

    name = var.policy_name
    num_loops = var.num_loops
    teams = [var.policy_teams]

    dynamic "rule" {
      for_each = local.teams
      escalation_delay_in_minutes = var.escalation_delay
      dynamic "target" {
         for_each = ??????
         content {
            type = var.target_type
            id = ??????
         }
       }
    }
}

???是我不确定的点。

我需要为列表中的每个项目创建一个规则(因此 [team1,team2] 和 [escalation_team]),然后对于这些列表中的每个项目,我需要为每个团队创建一个目标(因此规则 1 将有两个目标 - team1 和 team2 以及规则 2 将有一个目标,即 escalation_team)。

知道我该如何处理吗?

我正在使用 TF v0.12.20

这是我更新后的配置:

resource "pagerduty_escalation_policy" "policy" {
name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = local.teams
    escalation_delay_in_minutes = var.escalation_delay

    dynamic "target" {
      for_each = rule.value
      content {
        type = var.target_type
        id   = target.value
      }
    }
  }
}

编辑:更改locals.teamslocal.teams

标签: terraform

解决方案


如果我正确阅读了您的问题,我相信您想要以下内容

resource "pagerduty_escalation_policy" "policy" {
  name      = var.policy_name
  num_loops = var.num_loops
  teams     = [var.policy_teams]

  dynamic "rule" {
    for_each = locals.teams
    content {
      escalation_delay_in_minutes = var.escalation_delay

      dynamic "target" {
        for_each = rule.value
        content {
          type = var.target_type
          id   = target.value
        }
      }
    }
  }
}

请注意以下事项

  • 每个dynamic块必须有一个匹配的content
  • dynamic块引入了新名称,这些名称具有.key并且.value可用于访问正在循环的内容的属性。

我实际上无法运行它,所以如果它仍然错误,请告诉我,我会更新。


推荐阅读