Skip to main content
0 reactions

How to Use the file Function in OpenTofu

Card titled The file Function, labelled OpenTofu Functions, showing file(${path.module}/hello.txt) and the result Hello from a file!.
Read a text file into an OpenTofu string with the file function

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

SyntaxHCL
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

Step 1: Create the Files

In an empty folder, create hello.txt with one line:

hello.txtPlain text
Hello from a file!

Then create main.tf, with an output that reads the file:

main.tfHCL
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:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
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:

TerminalBash
tofu console
tofu consolePlain text
> 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

MistakeWhat happensDo this instead
Reading a file that a resource creates during the runIt 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 commandThe 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