File functions (file, templatefile) in Terraform - Time & Space Complexity
We want to understand how the time to read and process files grows as the file size or number of files increases.
Specifically, how the file and templatefile functions behave when used in Terraform.
Analyze the time complexity of reading and processing files using Terraform functions.
locals {
content1 = file("./config1.txt")
content2 = templatefile("./template.tpl", { var1 = "value" })
}
This code reads a plain text file and a template file with variables to produce strings.
Look at what happens when these functions run.
- Primary operation: Reading file contents from disk and processing template variables.
- How many times: Once per file or templatefile call.
As the size of the file grows, the time to read and process it grows roughly in direct proportion.
| Input Size (file size in KB) | Approx. Api Calls/Operations |
|---|---|
| 10 | Reads 10 KB, processes 10 KB |
| 100 | Reads 100 KB, processes 100 KB |
| 1000 | Reads 1000 KB, processes 1000 KB |
Pattern observation: Time grows linearly with file size.
Time Complexity: O(n)
This means the time to read and process files grows directly with the size of the file.
[X] Wrong: "Reading a file is always instant regardless of size."
[OK] Correct: Larger files take more time to read and process, so time grows with file size.
Understanding how file reading scales helps you design efficient infrastructure code and avoid slow deployments.
"What if we read multiple files in a loop? How would the time complexity change?"