Terraform Workspaces

Lasantha Sanjeewa Silva
3 min readMar 11, 2024

--

Terraform Workspaces helps us to manage multiple deployments of the same configuration. By default when we create cloud resources using Terraform resources are created under the default workspace. It helps us to resource allocation, regional deployments, and multi-account deployments. but workspaces have some drawbacks compared to the Modules. Modules will be discussed next article.

Create main.tf file and add s3 bucket creation Terraform configuration.

provider "aws" {
region = "us-east-2"
}

resource "aws_s3_bucket" "workspace" {
bucket = "hello-workspace-bucket"
}

Next, you can check the default workspace using the terraform workspace show command.

Create a new workspace using the terraform workspace new {workspace-name} command.

Check available environments using the terraform workspace list command.

Select workspace using terraform workspace select {workspace-name} command.

Also, You can delete the workspace using the terraform workspace delete {workspace-name} command.

Next, You can use the current workspace name using ${terraform.workspace} variable(Terraform workspaces interpolation). Let's modify the main.tf file with the terraform.workspace variable.

provider "aws" {
region = "us-east-2"
}

resource "aws_s3_bucket" "workspace" {
bucket = "hello-workspace-bucket-${terraform.workspace}"
}

After that run terraform plan. you can see the S3 bucket name plan as bucketname-dev.

Mainly terraform workspace has 2 drawbacks.

  • You cannot create a remote backend state file in a different location. All the state files go to one s3 bucket with the same key.
  • So many human errors. It means forgetting to switch the correct workspace. After that create resources in the wrong workspace.

In my opinion, Modules have more flexibility compared to workspace for managing separate remote state backend code.

A good article is related to Terraform WorkSpaces. https://spacelift.io/blog/terraform-workspaces

Thanks for reading the Article.

References https://developer.hashicorp.com/terraform/language/state/workspaces

Connect with me
LinkedIn https://www.linkedin.com/in/lasanthasilva
Twitter https://twitter.com/LasanthaSilva96

--

--