Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

747
Views
Terraform nested loop array of objects with an array in object

Just having this input in my module


 databases          = [
    {
      db_name = "test_0"
      db_owner   = "testu_user_0",
      extensions = ["unaccent"]
    },
    {
      db_name = "test_db"
      db_owner   = "test_user"
      extensions = ["uuid_ossp","pg_trgm"]
    }
  ]


And then i need to loop through and make specifiec extensions. How can i achieve that?

For the database creation it was pretty straightforward

resource "postgresql_database" "db" {
  for_each = {for db in var.databases : db.db_name => db}
  name  = each.key
  owner = postgresql_role.specific_role["${each.value.db_owner}"].name
  lifecycle {
    prevent_destroy = false
  }
}

But now when it comes to extensions im having a hard time to make it happen. I can see examples online, but they all use object with an array, not an array filled with objects and plus nested array inside.

# resource "postgresql_extension" "uuid_ossp" {
#   for_each = {for db in var.databases : db.db_name => db}
#   name     = "uuid-ossp"
#   database = each.key
# }

Please help

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You have to flatten your data structure, in locals for instance, and then use that in postgresql_extension:

locals {

    db_extentions = merge([
        for db in var.databases : 
        {
            for ext in db.extensions: 
            "${db.db_name}-${ext}" => {
                db_name = db.db_name
                db_owner = db.db_owner
                extension = ext
            }
        }
        ]...) # <-- the dots are important! Don't remove them
}

resource "postgresql_extension" "uuid_ossp" {
  for_each = local.db_extentions
  name     = each.value.extension
  database = each.value.db_name
}

The three dots are for Expanding Function Arguments.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!