templatestring Function
Note: The templatestring
function is intended for advanced use cases. Most use cases require only a string template expression. To render a template from a file, use the templatefile
function.
templatestring
renders a template given as a string value, using a supplied set of template variables.
templatestring(ref, vars)
The first parameter must be a direct reference to string value containing the template: for example, data.aws_s3_object.example.body
or local.inline_template
.
It is not valid to supply the template expression directly as the first argument:
# The following is not allowed
templatestring("Hello, $${name}", {
name = var.name
})
Instead of the above, you should use a normal string template expression:
"Hello, ${var.name}"
The templatestring
function is needed only when the template is available from a named object, such as a data resource, declared in the current module.
The template syntax is the same as for
string templates
in the main Terraform language, including interpolation sequences delimited with
${
... }
.
Example
The following example retrieves a template from S3 and dynamically renders it:
data "aws_s3_object" "example" {
bucket = "example-example"
key = "example.tmpl"
}
output "example" {
value = templatestring(data.aws_s3_object.example.body, {
name = var.name
})
}
For more examples of how to use templates, refer to the documentation for the templatefile
function.
Dynamic Template Construction
This function is primarily intended for rendering templates fetched as a single string from remote locations, often using data resources.
You can also use this as a way to construct a template dynamically and then render it, but we recommend treating that only as a last resort because the result tends to be hard to understand, hard to maintain, and fragile to unexpected input.
The restrictions on what kind of syntax is allowed in the first argument are a guardrail to help avoid those new to Terraform thinking that this function is the primary way to render templates in Terraform, but you can bypass those restrictions if you wish by writing an expression that builds a template dynamically and then assigning that expression to a local value. You can then use a reference to that local value as the first argument to templatestring
.
If you do choose to construct templates from parts dynamically, be mindful that Terraform has built-in functions that can interact with the local filesystem, and so maliciously-crafted input might produce a template whose result includes data from arbitrary files on the system where Terraform is running.
Related Functions
templatefile
reads a file from disk and renders its content as a template.