Search code examples
terraformterraform-cloud

for_each for a list of strings


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

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 main.tf 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?


Solution

  • You have only one instance of tfe_variable.names. Thus, there is nothing to iterate over. So you should just have:

    resource "random_pet" "pet" {
      prefix = tfe_variable.names.key
    }
    

    UPDATE

    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(yamldecode(file("names_list.yaml")))
      prefix = each.value
    }