No function named try when rendering template in terraform

I am rendering a .json document containing a policy:

data "template_file" "my_role_policy" {
  template = file("iam_role_policy_template.json")

  vars = {
    ACCESS_TO_SM   = false
    FOO            = bar

Within the iam_role_policy_template.json, I have the following snippet

        %{ if try(ACCESS_TO_SM, false) }
            "Effect": "Allow",
            "Action": [
            "Resource": "s3://my-bucket/my-path"
        %{ endif }

This is because there are other .tf files using the same template that (for some reason) may not pass this variable.

The plan fails with the error

Error: failed to render : <template_file>:20,15-18: Call to unknown function; There is no function named “try”.

I thought it was possible to use it in a template.

Hi @pantelis-karamolegko,

The hashicorp/template provider is a legacy provider that is no longer developed and is only available for installation for backward compatibility and for folks who are still using very old versions of Terraform that didn’t yet have built-in template rendering.

The functions available in this provider are essentially a frozen snapshot of what functions were available in some older version of Terraform (I forget which one) and I guess at that point try didn’t exist yet.

I would suggest migrating to the templatefile function instead, which is built right in to the Terraform language and so always has the same set of functions as are available in .tf files, aside from the exception that you can’t recursively called templatefile from inside a template.

1 Like