You should preprocess your YAML file with another programming language to create a format more aligned to what you want in Terraform.
Whilst Terraform has an expression language, it’s not a full programming language - in particular it can’t express something like “recursively descend through a data structure until it is fully flattened”.