Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Terraform nested loop
  • In <filename>.tf:
variable "users" {
  default = [
    {
      name       = "user1"
      databases  =  ["db1","db2"]
      password   = "change_me"
      privileges = ["CONNECT","CREATE","TEMPORARY"]
    },
    {
      name       = "user2"
      databases  =  ["db1","db3"]
      password   = "change_me"
      privileges = ["CONNECT","CREATE"]
    }
  ]
}

locals {
  db_grants = var.users == null ? [] : flatten([
    for index1,value1 in var.users : [
      for index2,value2 in value1.databases : {
        name       = value1.name
        database   = value2
        privileges = value1.privileges
      }
    ]
  ])
}
  • In Terraform console:
> local.db_grants
tolist([
  {
    "database" = "db1"
    "name" = "user1"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
      "TEMPORARY",
    ])
  },
  {
    "database" = "db2"
    "name" = "user1"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
      "TEMPORARY",
    ])
  },
  {
    "database" = "db1"
    "name" = "user2"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
    ])
  },
  {
    "database" = "db3"
    "name" = "user2"
    "privileges" = tolist([
      "CONNECT",
      "CREATE",
    ])
  },
])

more: https://blog.boltops.com/2020/10/06/terraform-hcl-nested-loops

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment