Skip to main content
0 reactions

How to Use path.module in OpenTofu

Card titled path.module, labelled OpenTofu Basics, showing value = path.module in modules/greeter/main.tf and the result modules/greeter.
Build file paths from a module’s own folder with path.module

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

SyntaxHCL
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

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:

modules/greeter/message.txtPlain text
Hello from the greeter module!
modules/greeter/main.tfHCL
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:

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

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

MistakeWhat happensDo this instead
Writing file("message.txt") inside a moduleThe 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.moduleThe 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