Skip to main content
Every OpenTofu configuration uses a state file to track and manage resources. By default, there’s a single workspace named default. To create multiple environments (for example, development and production) from the same configuration directory, you can use workspaces to isolate state files.

Listing the Default Workspace

Run:
The asterisk (*) indicates the currently active workspace.

Creating and Switching Workspaces

Create and switch to new workspaces:
Each workspace has its own isolated state. New workspaces start empty until you run tofu apply.
Listing again shows the active workspace:

Workspace Commands Reference

Using Workspaces in Configuration

Suppose your project directory at /root/opentofu/projects/webserver defines an AWS EC2 instance. You need:
  • Development: t2.micro
  • Production: m5.large
  • Region: ca-central-1
  • AMI: same for both environments
The image shows a directory structure for a Terraform project named "my-application" with files like variables.tf, main.tf, and terraform.tfstate. It also displays configurations for two environments, "development" and "production," specifying region, AMI, and instance type.
Update variables.tf to define instance_type as a map:
In main.tf, use lookup with terraform.workspace and add dynamic tags:

Verifying Workspace Values

Open the OpenTofu console to inspect workspace-specific values:

Applying Changes per Workspace

In the development workspace:
OpenTofu will plan:
Switch to production and apply:
OpenTofu will plan:

Local State File Organization

When using local state, OpenTofu organizes workspace-specific state under terraform.tfstate.d:
Each subdirectory holds the terraform.tfstate file for its workspace. That’s it for this lesson. See you in the next one!

Watch Video