Terraform Quickstart: Part 8 – Workspaces Explained
How to Use Terraform Workspaces to Manage Separate Environments
Introduction
Imagine you’re working on both dev and prod environments. They share the same Terraform code, but you need different settings. For example, dev needs smaller instances, while prod needs stricter rules. You don’t want to duplicate your code.
Workspaces address this issue by allowing you to manage multiple versions of the same infrastructure in an isolated way.
In this chapter, you’ll learn how Workspaces work.
Workspaces Overview
A workspace is a separate instance of the Terraform state. It’s like a folder where Terraform stores .tfstate
files.
When you run Terraform, it uses the current workspace to determine which state to read from and write to.
By default, Terraform uses a single workspace named default
.
Creating and Using Workspaces
Let’s review the most common commands you’ll need to manage workspaces.
Lists all available workspaces:
$ terraform workspace list
Create a new workspace:
$ terraform workspace new dev
Switch to a workspace:
$ terraform workspace select dev
Display the current workspace:
$ terraform workspace show
Delete a workspace (you need to switch to another one first):
$ terraform workspace delete dev
Example: Using Workspaces for Environments
Let’s say you have a module to deploy a GitHub repository. You can define variables that depend on the workspace:
variable "repo_name" {
default = "my-repo-${terraform.workspace}"
}
If you're in the dev
workspace, this becomes my-repo-dev
.
This lets you share one codebase but deploy environment-specific resources.
Workspace Limitations
Workspaces are great, but they’re not a silver bullet.
They don’t isolate everything — just the state.
You can't use different backends per workspace.
CI/CD pipelines often prefer to use separate directories or separate state files instead of workspaces.
So, use workspaces for lightweight environment management, but if you need full isolation (e.g. completely separate backends, providers, or credentials), go with a multi-directory setup.
Workspace Best Practices
Use workspaces for similar environments where the infra shape is the same.
Avoid using workspaces for totally different projects.
Always run
terraform workspace show
beforeapply
to avoid mistakes.Combine with variable files (
dev.tfvars
,prod.tfvars
) if needed.
Conclusion
In this lesson, you learned that workspaces let you keep multiple isolated states in one codebase without duplication. Still, use them carefully — and know when separate directories or repos are a better fit.