String chunking with max length

Hi guys, how are you?

I’m having difficulty developing logic with terraform functions.

I have a list of filters that I need to concatenate while the result is less than 100 characters.

locals {
    # I have this data
    data = [
        "(host eq domain1.example.com and path eq /foo)",
        "(host eq domain2.example.com and path eq /bar)",
        "(host eq domain1.example.com and path eq /baz)",
    ]

    # I need to concatenate the strings until the length is less than 100
    invalid_data_more_chars = join(" or ", local.data)

    # The expected output is
    expected_output = [
        "(host eq domain1.example.com and path eq /foo) or (host eq domain2.example.com and path eq /bar)",
        "(host eq domain1.example.com and path eq /baz)",
    ]
}

I thought about making an accumulator and concatenating and testing the length() of the string, but I can’t do that inside a for.

Anyone have any ideas?

Hi @kelvingl,

This sort of requirement is challenging in the Terraform language because it involves a “reduce”-type operation where multiple elements of an input collection need to aggregate as into a single element in the output.

One idea I have would be to optimistically concatenate them all into a single string first, and then use the regexall function on that string to apply a pattern that includes a length-constraining pattern. I’ve not tried it yet to see what exactly that might look like, but hopefully that’s an interesting idea to tug on.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.