Reading for_each data from a file

I am creating a bunch of random strings using resource_string resource block.
length is a required argument for this resource, and my goal is to read all the values for this variable from a file, using the file function. Is there a way to do it?

Here is my code, along with the error:

resource "random_string" "any_string" {
    for_each = toset(file("string_number_file.txt"))
    length = each.key
}
cat string_number_file.txt
"10","12","13"

Goal is to create three random_strings, with above lengths.

Here is the error with above code:

Error: Invalid function argument
│
│   on main.tf line 9, in resource "random_string" "any_string":
│    9:     for_each = toset(file("string_number_file.txt"))
│
│ Invalid value for "v" parameter: cannot convert string to set of any single type.  

Hi @JiJo333,

The file function “reads the contents of a file at the given path and returns them as a string”, so in this case your argument to the toset function is a string, and is why you get the error “cannot convert string to set”. If you have a simple series of comma separated values, you could use the split function to break up the string into a series of multiple strings, which would be a valid argument for toset.

1 Like

Thank you, let me give that a shot.

Thank you, that worked!