Paths¶
Terraform module paths refer to the hierarchical structure used to organize and reference resources within a Terraform configuration, facilitating resource management and interdependencies in infrastructure as code deployments.
Relative path¶
By default, Terraform interprets the path relative to the working directory from which it is running. A relative file path that contains multiple ../ segments is used to reference a module located in a parent directory of the current working directory. This is useful when working with complex project structures requiring shared modules across multiple projects or repositories.
For example, suppose we have the following directory structure:
+---modules
| \---ec2-instance
| | main.tf
| | variables.tf
|
+---projects
| \---project00
| \---prod
| \---services
| \---virtual-machines
| | main.tf
If we want to use the ec2-instance module from the virtual-machines\main.tf root module directory, we can reference it using a relative file path like this:
In this example, the ../../../../../../modules/ec2-instance file path goes up six directories to the root directory, then down into the modules/ec2-instance directory to find the main.tf and variables.tf files.
path reference¶
In some cases you may have a need to call a file that is located in the reusable module folder when running the root module. For example, this code defined in a simple root module would call the file user-data.sh assuming the file was in the root module folder and it would work. This fails when using reusable and root modules as the file exists in the reusable module but the relative path is from the root module.
To solve this we can call upon path.<TYPE> function to define the filesystem from which to find the file.
path.modulereturns the filesystem path of the module where the expression is defined
path.rootreturns the filesystem path of the root module
path.cwdreturns the filesystem path of the current working directory (similar to root but usfile for complex situations)
So to solve our problem, where the user-data.sh file is in the reusable module folder we can employ path.module in our command. This tells the Terraform code to locate the file in the reusable module folder and not the root module folder from where the Terraform is run (the relative path).