Jaimin Joshi
Jaimin Joshi

Reputation: 83

Can I use for_each meta-argument with file function?

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.   

Thanks in advance!

Upvotes: 1

Views: 188

Answers (1)

Marcin
Marcin

Reputation: 239000

In that case you can convert your file to json, and then use that:

resource "random_string" "any_string" {
    for_each = toset(jsondecode(format("[%s]",file("string_number_file.txt"))))
    length = each.key
}

Upvotes: 1

Related Questions