Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 225
pkaramol Avatar asked Feb 19 '20 14:02

pkaramol


Video Answer


2 Answers

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).

like image 78
Martin Atkins Avatar answered Sep 30 '22 07:09

Martin Atkins


Try command = "echo $(pwd) > somefile.txt"

like image 36
sadok-f Avatar answered Sep 30 '22 05:09

sadok-f