davidb
davidb

Reputation: 1603

Terraform dynamic blocks with nested list

I need to create an escalation policy in Pagerduty using Terraform. I want to dynamically create rule blocks and then within them target blocks with values from rule. I am not sure how to make the second call inside target block to make it dynamic. I have a list of teams within a list.

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 = ??????
         }
       }
    }
}

???? are the points I'm not sure about.

I need to create a rule for each item in a list(so [team1, team2] and [escalation_team]) and then for each item within those lists I need to create a target for each of the teams(so rule 1 will have two targets - team1 and team2 and rule 2 will have one target which is escalation_team).

Any idea how I could approach this?

I'm using TF v0.12.20

Here's my config after updating:

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

Edit: Changed locals.teams to local.teams

Upvotes: 2

Views: 5866

Answers (1)

mjgpy3
mjgpy3

Reputation: 8957

If I'm reading your question correctly, I believe you want something like the following

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

Note the following

  • Each dynamic block must have a matching content block
  • dynamic blocks introduce new names that have .key and .value which can be used to access properties of what's being looped over.

I can't actually run this so if it's still wrong let me know and I'll update.

Upvotes: 4

Related Questions