Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: How can I run a function on each element of a collection?

Tags:

terraform

I have a section in my terraform module which reads text from multiple files and joins them together.

foo = join("\n", [
  file('path/to/file1.txt'),
  file('path/to/file2.txt'),
  file('path/to/file3.txt'),
])

Its cumbersome to always list every file, and I would like to switch to using: fileset("path/to", "*.txt") to list all the files.

However, this gives me a list of file paths, which I can't give to file(). Is there some way I can run file() on each element of this list?

In other languages there is usually some map() function which is used to transform the elements of a collection, by calling a function on each item. I can't find anything like this in terraform. The closest thing I've found, is format_list() but that doesn't do what I need.

like image 508
Benjamin Tamasi Avatar asked Nov 26 '25 07:11

Benjamin Tamasi


1 Answers

Assuming you want to convert your list of file function returns from hardcoded inputs into a list of file function returns from dynamic inputs sourced from the fileset function, we can use a custom lambda for that:

[for text_file in fileset("path/to", "*.txt") : file(text_file)]

and this return value would be equivalent to:

[
  file('path/to/file1.txt'),
  file('path/to/file2.txt'),
  file('path/to/file3.txt'),
  ...
]

which you can input as an argument to join and assign to foo as you are doing in the question. More information on for expressions (the specific type of lambda function used here) can be found in the documentation. Note that these for expressions have implicit returns and are not "void" functions, making them equivalent to map as you requested, and not equivalent to an each.

like image 135
Matt Schuchard Avatar answered Nov 28 '25 23:11

Matt Schuchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!