
Terraform workspaces let you organize your deployments and keep state isolated between environments. This post covers what workspaces are, then shows how the workspace prefix feature lets you manage several workspaces from a single Terraform configuration.
Workspaces let you create separate instances of your infrastructure for different environments (e.g., development, staging, production) or for experimentation. Each workspace keeps its own Terraform state file, so the state of one environment stays separate from the others. They all share the same Terraform configuration files, which keeps the environments consistent.
Workspaces can be used with open-source Terraform in local operations or in a remote backend such as Scalr or Terraform Cloud. The concept between the two is similar in that it isolates Terraform state files, but workspaces in a remote operations backend are more advanced as the actual execution of runs happens within Scalr, which then enables more features such as integrations, remote state sharing, RBAC, and more.
The terraform workspace command can be used to interact with a workspace locally or in a remote backend. When working with Terraform, a default workspace is automatically created, which cannot be deleted. To create more workspaces, you have the following command line options:
The workspace prefix option allows you to set the common name across the workspaces so all you have to do is change the appended value. For example, you might have an application, let's call it "application-a", which has a dev, stage, and prod workspace associated with it. The actual core Terraform configuration files will remain the same, but some variable values might be different. In this example, we would have the following code set in our Terraform remote backend configuration file:
After setting the remote backend, a new workspace can be created with the following command:
terraform workspace new prod
Upon running terraform init, a new workspace will be seen in Scalr:

Example of a workspace in Scalr
All standard Terraform commands can be executed on this workspace, but it is highly advised to run terraform workspace show or terraform workspace list to always know which workspace you are operating in, especially if one is for a production environment:
That's all it takes to start using the Terraform workspace prefix option in a remote backend such as Scalr or Terraform Cloud.
Whether you run them remotely or locally, Terraform workspaces let you isolate the state file while reusing the same Terraform code. With a remote backend, the prefix option in the backend block gives you more flexibility to quickly switch between the Scalr or Terraform Cloud workspaces while you develop.
