Get current working directory in terraform

pkaramol picture pkaramol · Feb 19, 2020 · Viewed 11.5k times · Source

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?

Answer

Martin Atkins picture Martin Atkins · Feb 19, 2020

Terraform has a built-in object path that contains attributes for various paths Terraform knows about:

  • path.module is the directory containing the module where the path.module expression is placed.
  • path.root is the directory containing the root module.
  • path.cwd is 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).