Skip to content

Multiple Required Blocks

GlennChia edited this page Aug 8, 2021 · 2 revisions

This patten covers the following phrase in the Terraform Registry:

(Required) One or more <name of block> blocks as defined below.

Example:

(Required) One or more notification blocks as defined below.

Simple use case

In the configuration.tfvars file:

notifications = {
  contact_email = {
    enabled   = true
    threshold = 90.0
    operator  = "EqualTo"
    contact_emails = [
        "foo@example.com",
        "bar@example.com",
    ]
  }
  contact_role = {
    enabled   = true
    threshold = 85.0
    operator  = "EqualTo"
    contact_roles = [
        "Owner",
    ]
  }
}
  • In this example, there are 2 notification blocks within the notifications block
  • Note: Specifically for this example, each notification block should have a unique threshold and operator combination. If it's intended for them to be the same then one notification block can support a combination of contact_emails, contact_roles, and contact_groups.

In the resource file:

dynamic "notification" {
    for_each = var.settings.notifications

    content {
      operator  = notification.value.operator
      threshold = notification.value.threshold

      contact_emails = try(notification.value.contact_emails, [])
      contact_roles  = try(notification.value.contact_roles, [])
      enabled        = try(notification.value.enabled, true)
    }
  }
  • The for_each iterates through each notification block within the notifications object
  • In this for_each, the notifications is not destructured into its key and value because this is a required block and we want it to produce an error if a notifications variable is not injected into the resource.
Clone this wiki locally