I want to call terraform module in the next way:
module "database_role" {
source = "modules/roles"
project_id = "testid"
role_name = "testrole"
actions = {
action: ["ENABLE_PROFILER", "DROP_DATABASE"]
database_name: "test_db"
}
roles module definition i created is:
resource "mongodbatlas_custom_db_role" "custom_role" {
project_id = var.project_id
role_name = var.role_name
dynamic "actions" {
for_each = [for item in [var.actions] : item]
content {
actions {
action = lookup(actions.value, "action")
resources {
cluster = "false"
database_name = lookup(actions.value, "database_name")
}
}
}
}
}
as result i want to see actions properly generated:
actions {
action = "ENABLE_PROFILER"
resources {
cluster = "false"
database_name = "test_db"
}
}
actions {
action = "DROP_DATABASE"
resources {
cluster = "false"
database_name = "test_db"
}
}
I'm getting error: The given value is not suitable for child module variable "actions". What i'm doing wrong in module dynamic resource? Thanks
The flatten function could be used here.
I've below
actions
local var::Now, I'll flatten based on the size of
local.actions["action"]
to achieve the desired result. Once, I get the flattened list, I would loop through the list to create dynamic blocks.This would produce the required number of blocks I like::
This could be applied to create resources too. The key idea of working with nested or complicated loops is to flatten them into a list of resources or blocks, we create and then iterate through the flattened list with unique indexes as shown in above example.