How to Use templatefile Function in Terraform: Syntax and Example
Use the
templatefile function in Terraform to read a template file and replace placeholders with variable values. It takes the file path and a map of variables, returning the rendered string for use in your configuration.Syntax
The templatefile function requires two arguments: the path to the template file and a map of variables to replace in the template. It returns a string with all placeholders replaced by the provided values.
- templatefile(path, vars)
path: String path to the template file.vars: Map of variable names and their values.
terraform
templatefile("./example.tmpl", { name = "Alice", age = 30 })
Example
This example shows how to use templatefile to render a greeting message from a template file with variables.
terraform
variable "user_name" { default = "Alice" } variable "user_age" { default = 30 } output "greeting" { value = templatefile("./greeting.tmpl", { name = var.user_name, age = var.user_age }) } # Contents of greeting.tmpl: # Hello, my name is ${name} and I am ${age} years old.
Output
greeting = "Hello, my name is Alice and I am 30 years old."
Common Pitfalls
Common mistakes when using templatefile include:
- Incorrect file path causing file not found errors.
- Missing variables in the map leading to unresolved placeholders.
- Using incorrect syntax inside the template file (must use
${var}format).
Always verify the template file path is correct and all variables used in the template are provided in the map.
terraform
/* Wrong: Missing variable 'age' */ output "greeting_wrong" { value = templatefile("./greeting.tmpl", { name = "Alice" }) } /* Right: Provide all variables used in template */ output "greeting_right" { value = templatefile("./greeting.tmpl", { name = "Alice", age = 30 }) }
Quick Reference
Use this quick reference to remember how to use templatefile:
| Feature | Description |
|---|---|
| templatefile(path, vars) | Reads a template file and replaces variables. |
| path | String path to the template file. |
| vars | Map of variable names and values for replacement. |
| Template syntax | Use ${var} to reference variables inside the template. |
| Returns | A string with variables replaced. |
Key Takeaways
The templatefile function reads a file and replaces variables with values from a map.
Always provide all variables used in the template to avoid errors.
Use ${var} syntax inside the template file for placeholders.
Ensure the template file path is correct relative to your Terraform configuration.
templatefile returns a string that can be used in outputs, resources, or locals.