Loops over Tokens/Lists or Maps not known until apply-time (Like HCL `for`)


Is it possible to do HCL-like list or map comprehensions (for loops) to transform maps and lists when these maps or lists are outputs from a module which are not known until apply-time and so are Tokens?

A contrived example in HCL (imagining that the local list is an output of some module):

locals {
  emails = [
      name  = "fred",
      email = "fred@foo.com"
      name = "bob",
      email = "bob@bar.com"

output "email_to_name_mapping" {
  value = { for obj in local.emails : obj.email => obj.name }

Results in this output:

  + email_to_name_mapping = {
      + "bob@bar.com"  = "bob"
      + "fred@foo.com" = "fred"

I cannot work out how to do a similar thing in CDKTF with Python, either with Python natively, or even with a HCL escape-hatch.

from constructs import Construct
from cdktf import App, TerraformStack, TerraformOutput, TerraformLocal, Token

class MyStack(TerraformStack):
    def __init__(self, scope: Construct, id: str):
        super().__init__(scope, id)

        emails = TerraformLocal(self, "emails", [
                "name": "fred",
                "email": "fred@foo.com"
                "name": "bob",
                "email": "bob@bar.com"

        for v in emails.as_list:
            # Only one token in the list, I guess the token refers to the entire list, not a token per element, so I can't
            # perform Python list-comprehension on each element as a Token (and each list element as a token would not have
            # knowledge of the structure anyway, so no access to `name` or `email`)

        email_to_name_mapping_output = TerraformOutput(self, "email_to_name_mapping", value=emails) # As expected, it round-trips OK
        # email_to_name_mapping_output = TerraformOutput(self, "email_to_name_mapping", value=emails.as_list) # As expected, it round-trips OK
        # email_to_name_mapping_output.add_override("value", "{for obj in local.emails: obj.email => obj.name}") # Outputs the literal HCL

app = App()
MyStack(app, "cdktf-output-test")

In similar situations in the past, I have used the Fn API for related things (e.g. getting an element from a Token map not known until apply-time), but I do not think there are functions with the same utility as the native HCL for construct.

Anyone have any insight?


You should be able to put it in an escape hatch; otherwise, this isn’t currently supported.
AcmCertificateValidation: support complex for expressions · Issue #2178 · hashicorp/terraform-cdk · GitHub and Incorrectly generated iterator for ComplexList · Issue #2001 · hashicorp/terraform-cdk · GitHub are a couple issues referencing a similar idea.