Data structures for Dynamic Blocks

Hi,

I’m scratching my head a bit with dynamic (nested and not nested) blocks. Think about resources such as required_resource_access inside which you can define multiple resource_access blocks.

if I want to make required_resource_access dynamic, what would be the best data structure to use if I know the ids of these resources in advance? what would be the right iterators to use with such data structure?

Thanks in advance,

Dan

Hi @dansanabria!

Unless there are other requirements that call for a different structure, I’d default to mimicking the structure of the nested as closely as possible by using lists to represent sequences of blocks of the same type and objects to represent the blocks themselves. For example:

  [
    {
      resource_app_id = "example"
      resource_access_rules = [
        {
          id   = "example1"
          type = "Role"
        },
        {
          id   = "example2"
          type = "Role"
        },
      ]
    }
  ]

If the values were coming in via an Input Variable, the above data structure would have the following type constraint:

variable "required_resource_access" {
  type = list(object({
    resource_app_id = string
    resource_access_rules = list(object({
      id   = string
      type = string
    })
  })
}

To use this data structure in your azuread_application resource configuration you’d then have two levels of dynamic:

resource "azuread_application" "example" {
  # ... other arguments ...

  dynamic "required_resource_access" {
    for_each = var.required_resource_access
    content {
      resource_app_id = required_resource_access.value.resource_app_id

      dynamic "resource_access" {
        for_each = required_resource_access.value.resource_access_rules
        content {
          id   = resource_access.value.id
          type = resource_access.value.type
        }
      }
    }
  }
}
3 Likes

T H A N K Y O U !!!

I was on the right track with the double-level/nested of dymanic but was lacking in my understanding of type constraints and validating the “right” input data structure.

This produces the expected plan output (you are just missing closing ‘)’ on your type definition).

Thanks again,

Dan

Ahh yes, sorry for the syntax errors… easy for those to creep in when editing code in the forum editor :roll_eyes: . I’m glad you got something that works!

1 Like