Search code examples
terraformterraform-template-file

Correct way to Terraform template_provider data source output


I'm trying to render the output of a map using a template in Terraform: variable "default_tags" { type = "map" default = { "tag1" ="Tag A", "tag2" ="Tag B" } } Define a template_file data source to render the map:

```
data "template_file" "test" {
  template = "${data}"
  vars {
    data = "${join(",", formatlist("key: %s, val: %s. ",     keys(var.default_tags), values(var.default_tags)))}"
  }
}
```

My output bloc should look like this:

```
 output "default_tags_rendered" {
  value="${data.template_file.test.rendered}"
 }
```

However I get this error when planning:

 ```
 Error: data.template_file.test: 1 error(s) occurred:
 * data.template_file.test: invalid variable syntax: "data". Did you mean      'var.data'? If this is part of inline `template` parameter
 then you must escape the interpolation with two dollar signs. For
 example: ${a} becomes $${a}.
 ```

What would be the correct way to output the rendered template?


Solution

  • This may be better suited to using local values like so

    locals {
      data = "${join(",", formatlist("key: %s, val: %s. ", keys(var.default_tags), values(var.default_tags)))}"
    }
    
    output "default_tags_rendered" {
     value="${local.data}"
    }
    

    Reasoning is because the template_file provisioner is mainly used for files (or inline templates) that need to be run through the standard interpolation syntax. In this case, you don't have any variables to be interpolated in a template - you have a variable coming in and you need to mutate it's value.