Terraform partial remote backend cannot contain interpolations?

3.3k Views Asked by At

I am trying to configure a Terraform enterprise workspace in Jenkins on the fly. To do this, I need to be able to set the remote backend workspace name in my main.tf dynamically. Like this:

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


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

Now when I run:

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

I get:

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

Is what I want to do possible with terraform?

2

There are 2 best solutions below

4
Claire Bellivier On BEST ANSWER

You cann't put any variables "${var.workspace_name}" or interpolations into the Backend Remote State Store. However, you can create a file beside with your Backend values, it could look like this into the main.tf file:

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

and into a dev.backend.tfvars for instance:

bucket         = "BUCKET_NAME"

encrypt        = true

key            = "BUCKET_KEY"

dynamodb_table = "DYNAMODB_NAME"

region         = "AWS_REGION"

role_arn       = "IAM_ROLE_ARN"

You can use partial configuration for s3 Backend as well. Hope it'll help.

0
Nicolas Le Gorrec On

Hey I found the correct way to do this:

While the syntax is a little tricky, the remote backend supports partial backend initialization. What this means is that the configuration can contain a backend block like this:

terraform {
  backend "remote" { }
}

And then Terraform can be initialized with a dynamically set backend configuration like this (replacing ORG and WORKSPACE with appropriate values):

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