file reads a text file and returns what’s in it as a string, so you can keep long text, such as a page or a script, in its own file.
Syntax
file(<PATH>)
<PATH>: the path of the file. A relative path starts from the folder you run OpenTofu® in, so write"${path.module}/…"to start from the configuration’s own folder.
The docs say the file must be UTF-8 text and must already exist when the run starts: file Function (opens in a new tab).
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Create the Files
In an empty folder, create hello.txt with one line:
Hello from a file!
Then create main.tf, with an output that reads the file:
output "greeting" {
value = file("${path.module}/hello.txt")
}
Step 2: Apply It
This configuration uses no providers, so tofu apply works without tofu init. Run it and type yes:
tofu apply
Outputs:
greeting = <<EOT
Hello from a file!
EOT
OpenTofu shows the text with its final line break, as a heredoc.
Step 3: Try It in tofu console
Start tofu console in the same folder and read the file again, then a file that doesn’t exist:
tofu console
> file("hello.txt")
<<EOT
Hello from a file!
EOT
> file("missing.txt")
╷
│ Error: Invalid function argument
│
│ on <console-input> line 1:
│ (source code not available)
│
│ Invalid value for "path" parameter: no file exists at "missing.txt"; this function works only with files that are distributed as part of the configuration source code, so if this file will be created by a resource in this configuration you must instead obtain this result from an attribute of that
resource.
╵
> exit
Clean Up
Run tofu destroy and type yes to remove the output from the state, then delete the folder.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Reading a file that a resource creates during the run | It fails: the docs say the file must exist when the run starts. | Read the resource’s attribute instead. |
| Using a path relative to where you run the command | The path breaks when you run OpenTofu from another folder. | Start it with ${path.module}. |
FAQ
Can file read a template with values in it?
It reads the text as it is. To fill in values, the docs point to templatefile.
Can it read images?
No. It reads UTF-8 text; the docs name filebase64 for other files.
Conclusion
file(<PATH>) returns the text of a file that exists before the run; start its path with ${path.module}.
Additional Resources
OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.
0 comments