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
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.