Trouble flattening nested objects of lists

Hi

I’m having trouble correctly flattening some data for use with for_each.

I’m close but not quite there: -

variable definition:

variable “team_accounts” {
type = map(object({
roles = map(object({
services = list(string)
policies = list(string)
}))
}))
}

terrafrom.tfvars:

team_accounts = {
“client1” = {
accountid = “111111”
roles = {
“adm” = {
services = [“ec2”, “dynamodb”]
policies = [“policy1”]
},
“dev” = {
services = [“ec2”]
policies = [“policy2”]
}
}
},
“client2” = {
accountid = “222222”
roles = {
“adm” = {
services = [“ecr”, “dynamodb”]
policies = [“policy1”]
},
“dev” = {
services = [“ecr”, “dynamodb”]
policies = [“policy3”]
}
“audit” = {
services = [“cloudwatch”]
policies = [“policy4”]
}
}
}

main.tf

locals {
accounts_roles_services = flatten([for account, value in var.team_accounts:
flatten([for desired_role, useroles in value.roles:
flatten([for accountroles, services in useroles:
[for service in services: {
“account” = account
“role” = desired_role
“service” = service
}]
])
])
])
}
output “accounts_roles_services” {
value = local.accounts_roles_services
}

Output here gives instance block for each possible outcome but includes all values for both services and policies, want to restrict to just services

i.e accounts_roles_services = [
+ {
+ account = “client1”
+ role = “admin”
+ service = “policy1”
},
+ {
+ account = “client1”
+ role = “admin”
+ service = “ec2”
},
… instance for each possible outcome including service taking on policies when do not want that.

Any ideas ? Many thanks Paul