'Get current working directory in terraform
I am running Terraform using Terragrunt so I am not actually certain about the path that the terraform is invoked from.
So I am trying to get the current working directory as follows:
resource null_resource "pwd" {
triggers {
always_run = "${uuid()}"
}
provisioner "local-exec" {
command = "echo $pwd >> somefile.txt"
}
}
However the resulting file is empty.
Any suggestions?
Solution 1:[1]
Terraform has a built-in object path that contains attributes for various paths Terraform knows about:
path.moduleis the directory containing the module where thepath.moduleexpression is placed.path.rootis the directory containing the root module.path.cwdis the current working directory.
When writing Terraform modules, we most commonly want to resolve paths relative to the module itself, so that it is self-contained and doesn't make any assumptions about or cause impacts to any other modules in the configuration. Therefore path.module is most often the right choice, making a module agnostic to where it's being instantiated from.
It's very uncommon to use the current working directory because that would make a Terraform configuration sensitive to where it is applied, and likely cause unnecessary resource changes if you later apply the same configuration from a different directory or on a different machine altogether. However, in the rare situations where such a thing is needed, path.cwd will do it.
path.module and path.root are both relative paths from path.cwd, because that minimizes the risk of inadvertently introducing details about the system where Terraform is being run into the configuration. However, if you do need an absolute module path for some reason, you can use abspath, like abspath(path.module).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
