1

我想在我的 TF 文件中使用环境变量。我如何在这些文件中提及它们?

我使用 Terraform 云并在环境变量部分定义变量。这意味着我不使用我的 cli 来运行 terraform commands 命令(没有 export TF_VAR 和没有 -var 或 -var-file 参数)。

我在论坛和文档中都没有找到任何答案。

编辑: 也许如果我详细说明我所做的事情会很清楚。

所以我有 2 个名为“用户名”和“密码”的环境变量

这些变量在 Terraform Cloud 的环境变量部分中定义。

在我的 main.tf 文件中,我创建了一个应该使用这些用户名和密码变量创建的 mongo 集群。在主 variables.tf 文件中,我将这些变量定义为:

variable "username" {
  type = string
}

variable "password" {
  type = string
}

我的 main.tf 文件如下所示:

module "eu-west-1-mongo-cluster" {
...
...
  username = var.username
  password = var.password
}

在 mongo 子模块中,我在 variables.tf 文件中将它们定义为类型字符串,并在子模块的 mongo.tf 文件中将它们定义为 var.username 和 var.password

谢谢 !

4

2 回答 2

1

我认为 Terraform Cloud 不支持您尝试做的事情。您正在Environment VariablesUI 中进行设置,但您需要进行设置Terraform Variables(参见屏幕截图)。对于 Terraform Cloud 后端,您需要动态创建,远程后端不支持*.auto.tfvars通常的-var="myvar=123"或当前支持的。以下错误消息是在使用值运行 terraform 1.0.1 时从 CLI 生成的:TF_VAR_myvar=123terraform.tfvars-var

│ Error: Run variables are currently not supported
│ 
│ The "remote" backend does not support setting run variables at this time. Currently the
│ only to way to pass variables to the remote backend is by creating a '*.auto.tfvars'
│ variables file. This file will automatically be loaded by the "remote" backend when the
│ workspace is configured to use Terraform v0.10.0 or later.
│ 
│ Additionally you can also set variables on the workspace in the web UI:
│ https://app.terraform.io/app/<org>/<workspace>/variables

我的用例是在 CI/CD 管道中使用远程 Terraform Cloud 后端的 CLI,因此创建了*.auto.tfvars例如:

# Environment variables set by pipeline
TF_VAR_cloudfront_origin_path="/mypath"

# Dynamically create *.auto.tfvars from environment variables
cat >dev.auto.tfvars <<EOL
cloudfront_origin_path="$TF_VAR_cloudfront_origin_path"
EOL

# Plan the run
terraform plan

在此处输入图像描述

于 2021-06-26T12:39:22.453 回答
0

根据https://www.terraform.io/docs/cloud/workspaces/variables.html#environment-variables,terraform 将导出所有提供的变量。

因此,如果您已经定义了环境变量TF_VAR_name,那么您应该能够var.name在 terraform 代码中使用。

希望这可以帮助。

于 2019-11-14T09:24:18.647 回答