Dynamic backend configuration

Hi there,

I’m trying to have a single tf file that can cater to local state or remote AWS S3 for a build pipeline running in a container.

I tried having a dynamic block:

dynamic “s3_backend” {
for_each = var.use_remote_terraform_state == false ? : [1]
terraform {
backend “s3” {
bucket = var.terraform_state_s3_bucket
key = var.terraform_state_s3_key
region = var.terraform_state_s3_region
dynamodb_table = var.terraform_state_dynamo_table
encrypt = true
}
}
}

However this results in the error:
Error: Unsupported block type

on main.tf line 10:
10: dynamic “s3_backend” {

Blocks of type “dynamic” are not expected here.

Any suggestions on how to achieve this?

Thanks in advance.

Tim

Hi @wonboyn,

What you are trying to achieve here is not possible. Each configuration has one backend statically associated with it.

If you want to use the same configuration with multiple backends then the usual approach is to factor those common parts out into a shared module and then call it from two different configurations, each of which has a different backend configuration.

terraform {
  backend "s3" {
    # ...
  }
}

module "example" {
  source = "../modules/example"

  # ...
}
terraform {
  backend "local" {
    # ...
  }
}

module "example" {
  source = "../modules/example"

  # ...
}