2

我正在尝试在 Jenkins 中动态配置 Terraform 企业工作区。为此,我需要能够在 main.tf 中动态设置远程后端工作区名称。像这样:

# Using a single workspace:
terraform {
  backend "remote" {
    hostname = "app.xxx.xxx.com"
    organization = "YYYY"


    # new workspace variable
    workspaces {
      name = "${var.workspace_name}"
    }
  }
}

现在当我运行时:

    terraform init -backend-config="workspace_name=testtest"

我得到:

Error loading backend config: 1 error(s) occurred:

* terraform.backend: configuration cannot contain interpolations

The backend configuration is loaded by Terraform extremely early, before
the core of Terraform can be initialized. This is necessary because the backend
dictates the behavior of that core. The core is what handles interpolation
processing. Because of this, interpolations cannot be used in backend
configuration.

If you'd like to parameterize backend configuration, we recommend using
partial configuration with the "-backend-config" flag to "terraform init".

我想用 terraform 做什么?

4

2 回答 2

4

您不能将任何变量"${var.workspace_name}"或插值放入后端远程状态存储中。但是,您可以在 Backend 值旁边创建一个文件,它在main.tf文件中可能如下所示:

# Terraform backend State-Sotre
terraform {
  backend "s3" {}
}

并进入dev.backend.tfvars例如:

bucket         = "BUCKET_NAME"

encrypt        = true

key            = "BUCKET_KEY"

dynamodb_table = "DYNAMODB_NAME"

region         = "AWS_REGION"

role_arn       = "IAM_ROLE_ARN"

您也可以对 s3 后端使用部分配置。希望它会有所帮助。

于 2019-04-03T16:59:03.943 回答
0

嘿,我找到了正确的方法:

虽然语法有点棘手,但远程后端支持部分后端初始化。这意味着配置可以包含这样的后端块:

terraform {
  backend "remote" { }
}

然后可以使用这样的动态设置后端配置来初始化 Terraform(用适当的值替换 ORG 和 WORKSPACE):

terraform init -backend-config "organization=ORG" -backend-config 'workspaces=[{name="WORKSPACE"}]'
于 2019-04-04T20:52:44.150 回答