Can't use null as result in rendering

Hi.
I’m trying to render template file test.tpl
{ "CERTFILE": ${test} }
with main.tf
output "test" { value = templatefile("test.tpl", { test=null }) }

And got an error:

$ terraform apply

Error: Error in function call

on main.tf line 2, in output “test”:
2: value = templatefile(“test.tpl”,
3:
4:
5:

Call to function “templatefile” failed: test.tpl:2,17-21: Invalid template
interpolation value; The expression result is null. Cannot include a null
value in a string template…

But it works fine when template file looks
{ "CERTFILE": null }
I need to have exactly the null.
terraform -version
Terraform v0.12.28

Thanks

Templates are string-interpolated, so you cannot pass null. But in this case, since your template does not have quotes around the value, to render the result you want you can bind the string "null". Like this:

output "test" { value = templatefile("test.tpl", { test="null" }) }
$ terraform apply -auto-approve

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test = { "CERTFILE": null }

However, this looks like a JSON object. In that case, I would recommend using the jsonencode function to generate the object. This is much less error-prone than trying to write string templates to create JSON.

Example config:

output "test" {
  value = jsonencode(
    {
      "CERTFILE" : null,
    }
  )
}
1 Like

You’ve saved me. Thanks a lot.