path.module is the path of the folder that holds the module where you write it. Starting a file path with it makes the path work wherever you run OpenTofu® from, and inside every module.
Syntax
path.module
"${path.module}/<FILE>"
path.module: the module’s folder. In the root module it’s., the current configuration folder.<FILE>: a file inside that folder, such as a template or a script.
It’s one of the values in Filesystem and Workspace Info (opens in a new tab) in the OpenTofu docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Create a Root and a Child Module
In an empty folder, create a folder modules/greeter with a text file and a main.tf that reads it:
Hello from the greeter module!
output "where" {
value = path.module
}
output "message" {
value = file("${path.module}/message.txt")
}
Then create the root main.tf, which calls the module and shows both paths:
module "greeter" {
source = "./modules/greeter"
}
output "root_path" {
value = path.module
}
output "module_path" {
value = module.greeter.where
}
output "module_message" {
value = module.greeter.message
}
Step 2: Initialize and Apply
tofu init installs the local module; then apply and type yes:
tofu init
tofu apply
Outputs:
module_message = <<EOT
Hello from the greeter module!
EOT
module_path = "modules/greeter"
root_path = "."
In the root module, path.module is .; in the child module, it’s modules/greeter, so file finds message.txt next to the module’s own files.
Clean Up
Run tofu destroy and type yes to remove the outputs from the state, then delete the folder.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing file("message.txt") inside a module | The path starts from where you run OpenTofu, not from the module, so the file isn’t found. | Write "${path.module}/message.txt". |
Writing files into path.module | The docs advise against it: several uses of one local module share the same folder. | Use it for reading files that ship with the module. |
FAQ
What’s the difference from path.root?
path.root is always the root module’s folder; path.module is the folder of the module the expression is in.
Is path.module an absolute path?
No. Here it was . and modules/greeter, relative paths.
Conclusion
Start file paths with ${path.module} so a module always finds its own files.
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