Skip to content
Latchkey

Terraform templatefile() Errors in CI

templatefile(path, vars) renders a template at plan time. It errors when the template references a variable not in the vars map, the file path is wrong, or the template’s ${}/%{} syntax is malformed.

What this error means

plan fails calling templatefile() - a variable used in the template is absent from the vars map, the file cannot be read, or a template directive is invalid. The render never completes.

terraform output
Error: Error in function call

  on main.tf line 3, in locals:
   3:   user_data = templatefile("${path.module}/init.tpl", { name = "web" })

Call to function "templatefile" failed: ${path.module}/init.tpl:2,14-18: Invalid
template interpolation value; The expression result is null. Cannot include a
null value in a string template. (vars: "port" is not defined)

Common causes

Template variable not supplied

The template references ${port} but the vars map passed to templatefile() does not include port, so rendering fails on the undefined reference.

Wrong file path

A relative path that is not anchored on ${path.module} resolves against the working directory and may not exist in CI.

Invalid template directive syntax

A malformed %{ for ... } / %{ endfor } or an unescaped $${}/%%{} literal breaks template parsing.

How to fix it

Pass every referenced variable and anchor the path

Supply all template variables in vars and use ${path.module} so the path resolves regardless of working directory.

main.tf
locals {
  user_data = templatefile("${path.module}/init.tpl", {
    name = "web"
    port = 8080
  })
}

Validate template directives

  1. Confirm every ${...} reference in the template has a matching key in vars.
  2. Balance %{ for }/%{ endfor } and %{ if }/%{ endif } directives.
  3. Escape literal ${/%{ sequences you do not want interpolated.

How to prevent it

  • Pass a complete vars map matching every template reference.
  • Anchor template paths on ${path.module}.
  • Keep template control directives balanced and escape literals.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →