For_each for a list of strings variable

I am creating a variable in terraform cloud and using that variable as an input to create a random_pet resource.

Goal is to create below variable:
name_prefixes = [“tfe”,“tfc”,“ansible”,“puppet”]
random_pet resource should iterate over above four elements, and create four resources.

Code is as below:

resource "tfe_variable" "names" {
  key          = "name_prefixes"
  value        = jsonencode(yamldecode(file("names_list.yaml")))
  workspace_id = "ws-id"
  hcl          = true
  category     = "terraform"  

resource "random_pet" "pet" {
  for_each = toset(tfe_variable.names.key)
  prefix = each.key

cat names_list.yaml

- "tfe"
- "tfc"
- "ansible"
- "puppet"

I am getting an error:

Error: Invalid function argument
on line 12, in resource "random_pet" "pet":
  for_each = toset(tfe_variable.names.key)
Invalid value for "v" parameter: cannot convert string to set of any single type.

Can you please suggest?

Why are you jsonencode?

Hi @cregkly, I am using jsonencode to convert it into an HCL variable (name_prefixes
is HCL)

That isn’t what jsonencode does. Try it without.

I tried it without jsonencode, passing it as a string and still the same error.

The general structure of this example doesn’t make sense … You’re setting an HCL-formatted TFE/TFC variable by uploading HCL as a string, but nowhere is that variable being accessed as a Terraform input variable, so that HCL is never being parsed and made available within this Terraform plan.

This example is too much of a “toy” or “demo” for me to guess what you want from it, but maybe try just deleting all reference to TFE/TFC completely, and just referencing the result of yamldecode directly.

1 Like