#33272·terraform

Accept recursive calls to templatefile()

Author: ExchizzCreated May 27, 2023Updated Sep 18, 2026
Labelsenhancementnew

Terraform Version

bash
Terraform v1.6.0-dev
on windows_amd64

Use Cases

We're going to use templatefile() for creating Azure Devops templates. For easier maintenance we want to be able to import templates from templates.

Attempted Solutions

main.tf

resource "local_file" "pipeline-templater" {
  content  = templatefile("pipeline.tftpl", { vars = local.variables })
  filename = "pipeline.yaml"
}

pipeline.tftpl

${ templatefile("template_header.tftpl",{vars = vars}) }
<pipeline goes here>

template_header.tftpl

pool: ${vars.agent_pool}

That gives the following error:

Error in function call; Call to function
│ "templatefile" failed: cannot recursively call templatefile from inside templatefile call..

Proposal

It is well documented behavior:

https://developer.hashicorp.com/terraform/language/functions/templatefile

The template may also use any other function available in the Terraform language, except that recursive calls to templatefile are not permitted. 

From the source code: https://github.com/hashicorp/terraform/blob/bc216caa65e0ca5e07dbfbbe5833790562091a5d/internal/lang/funcs/filesystem.go#LL69C1-L71C38

// As a special exception, a referenced template file may not recursively call
// the templatefile function, since that would risk the same file being
// included into itself indefinitely.

I don't think terraform should decided whether I can call templatefile() from a template or not. It works if I remove that check from the source code and compile terraform, so I suggest some mechanism should be implemented that informs the user, if the user has accidentally imported the same file info itself. Some recursion limit maybe ?

References

No response