Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access attributes on a list of objects in terraform

Trying to create a dynamic block based on a list of objects.

Here is the attempt

data "vault_policy_document" "this" {

  dynamic "rule" {
    for_each = {
      for p in var.policy : format("%s-%s", p.path, join(",", p.capabilities)) => p
    }

    content {
      path         = rule.value.path
      capabilities = rule.value.capabilities
    }
  }
}

and here is the input var.policy

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


policy-test-1 = [
  {
      capabilities = [
          "create",
          "read",
      ]
      path         = "/foo/lala"
  },
  {
      capabilities = [
          "create",
          "read",
      ]
      path         = "/bar/lala"
  },
]

Its declaration

variable "policy" {
  description = "The policy to be created"
  type = map(list(object({
    path = string
    capabilities = set(string)
  })))

Why does this fail with

5:       for p in var.policy : format("%s-%s", p.path, join(",", p.capabilities)) => p
│
│ Can't access attributes on a list of objects.

Isn’t each item in the list (i.e. the p in the for loop) an object with paths and capabilities attributes?

>Solution :

You need double four loop, because you have a map of lists, along with the merge to flatten it:

    for_each = merge([
             for p in var.policy: {
                for statement in p: 
                   format("%s-%s", statement.path, join(",", statement.capabilities)) => statement
             }   
         ]...)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading