Join for_each data values


I want to for_each over a map, create a data resource for each item in the map
then join the data resources into a list so I can write it to a local file resource.
Lets keep it simple for this example. The join below works if I use count but I need
to use for_each for other reasons.



My data block where is keyed on hostname.

data "template_file" "hosts" {
  for_each = {
  for k, v in : k => v
  template = file("${path.module}/hosts.tpl")
  vars = {
    hostname = each.key

I create all the data resources for all my hosts then I want to create a list of them and I will use another template file and create a local file resource with the list of hosts.


My other data block

data "template_file" "host_list" {
  for_each = {
  for k, v in : k => v
  template = file("${path.module}/host_list.tpl")
  vars = {
    hosts = join("", data.template_file.hosts.*.rendered)   # <<< how do I join all my data values into a list?

I get the error

Error: Unsupported attribute
│   on hosts/ line 136, in data "template_file" "host_list":
│  136:     hosts = join("", data.template_file.hosts.*.rendered)
│ This object does not have an attribute named "rendered".

Thank you

This part can be simplified to just:

  for_each =

You shouldn’t include a for_each in this block at all, since there’s no point in re-making the list, for each item in the list.

The .* operator only works on lists, but when you are using for_each, resources are maps. You need to get the values list from the map first:


Also consider replacing the .* operator with the [*] operator, which has the same effect in this case, but in general tends to behave more as humans expect, when the expression after it gets more complex.

Also consider migrating from the template_file data source to the more modern built-in templatefile function - templatefile - Functions - Configuration Language | Terraform by HashiCorp

Thank you @maxb I will give this a try. Do you know if the * notation is documented somewhere for lists and maps?