Terraform 部分远程后端不能包含插值?

Terraform partial remote backend cannot contain interpolations?

我正在尝试在 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 做的事是可能的吗?

您不能将任何变量 "${var.workspace_name}" 或插值放入后端远程状态存储。 但是,您可以在后端值旁边创建一个文件,它在 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"

您也可以使用 partial configuration for s3 Backend。 希望对你有帮助。

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

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

terraform {
  backend "remote" { }
}

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

terraform init -backend-config "organization=ORG" -backend-config 'workspaces=[{name="WORKSPACE"}]'