Can I configure Terraform to not use "env:" in the path for a workspace's state file path on S3?

Viewed 2111

I am using S3 for a remote state with Terraform.

When I use a Terraform workspace then the path for the state file for the environment ends up being s3://<bucket>/env:/<workspace>/<key> where <bucket> and key are specified in a terraform block. For example, with the below Terraform HCL:

terraform {
  backend "s3" {
    bucket = "devops"
    key = "tf-state/abc/xyz.tfstate"
    region = "us-east-1"
  }
}

If we're using a Terraform workspace, like so:

$ terraform workspace new myapp-dev
$ terraform workspace select myapp-dev
$ terraform init
$ terraform apply

then we'll end up with the Terraform state file in the following path: s3://devops/env:/myapp-dev/tf-state/abc/xyz.tfstate

It seems that Terraform by default uses a subdirectory named env: under which it manages state files associated with workspaces. My question is can we add anything into the Terraform configuration that will allow us some control over the env: part of this?

1 Answers

When using a non-default workspace, the state path in the S3 bucket includes the value of workspace_key_prefix, like:

/<workspace_key_prefix>/<workspace_name>/<key>

The default value of workspace_key_prefix is env:. You could change your configuration to something like:

terraform {
  backend "s3" {
    bucket = "devops"
    key = "terraform.tfstate"
    region = "us-east-1"
    workspace_key_prefix = "tf-state"
  }
}

Then, when using the myapp-dev workspace, the state file will be s3://devops/tf-state/myapp-dev/terraform.tfstate.

Related