如何从不同的文件夹 运行 terraform init?

How do I run terraform init from a different folder?

我想为 CI/CD 目的编写 terraform 脚本,我不喜欢在脚本中进行 CDing,我宁愿有特定的路径。

我试过了terraform init c:\my\folder\containing\tf-file

但是 运行 将 .terraform 文件夹放入我的 cwd。

更新:Terraform cli 现在支持 -chdir=PATH/TO/TF_files

https://www.terraform.io/cli/commands#switching-working-directory-with-chdir

By default, terraform init assumes that the working directory already contains a configuration and will attempt to initialize that configuration.

Optionally, init can be run against an empty directory with the -from-module=MODULE-SOURCE option, in which case the given module will be copied into the target directory before any other initialization steps are run.

https://www.terraform.io/docs/commands/init.html

terraform init 命令中的 [DIR] 选项告诉 terraform 从哪里处理 tf 文件,但不告诉它在哪里存储状态文件。如果您想更改存储状态文件的本地路径,请在 main.tf 中添加一个部分来配置后端路径。

terraform {
  backend "local" {
    path = "relative/path/to/terraform.tfstate"
  }
}

我还没有真正尝试过这个,但你可以从命令行传递路径:

-backend-config="path=/foo"

我知道这是一个旧线程但是...您要查找的命令是:

terraform -chdir=environments/production apply

请看这个link for help with the global option -chdir=":

Quote from the actual Terraform site:

The usual way to run Terraform is to first switch to the directory containing the .tf files for your root module (for example, using the cd command), so that Terraform will find those files automatically without any extra arguments.

In some cases though — particularly when wrapping Terraform in automation scripts — it can be convenient to run Terraform from a different directory than the root module directory. To allow that, Terraform supports a global option -chdir=... which you can include before the name of the subcommand you intend to run:

terraform -chdir=environments/production apply The chdir option instructs Terraform to change its working directory to the given directory before running the given subcommand. This means that any files that Terraform would normally read or write in the current working directory will be read or written in the given directory instead.

不带选项指定目录

terraform apply [options] ./path-to-dir

或者您可以使用 -chdir 选项

terraform -chdir="./path-to-dir" apply

Terraform 默认假定您在 terraform 文件所在的目录中 运行 执行命令,但如果您在不同的目录并且想要对位于其他地方的文件执行 运行 terraform 命令,您可以执行以下操作:

terraform -chdir=[path_to_dir] [command_to_run]

示例:

terraform -chdir=terraform/ plan
terraform -chdir=terraform/ apply