In this guide, you’ll learn how to create, select, and manage OpenTofu workspaces to maintain separate state files for multiple deployments of the same configuration. By the end, you’ll deploy a payroll application across three regions—US, UK, and India—using a single Terraform-compatible codebase.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Prerequisites
- OpenTofu CLI installed and available in your
PATH. - A sample project directory named
project-sapphire. - Access to an S3-like backend (e.g., LocalStack) for state storage.
1. List the Default Workspace
Navigate to your project directory and list available workspaces. By default, OpenTofu starts with thedefault workspace.
2. Create New Workspaces
Isolate state per region by creating three workspaces:us-payroll, uk-payroll, and india-payroll.
| Workspace | Description |
|---|---|
| default | Default environment |
| us-payroll | State for US payroll deployment |
| uk-payroll | State for UK payroll deployment |
| india-payroll | State for India payroll deployment |
3. Select a Workspace
Switch to theus-payroll workspace before running any commands:
4. Understand Workspace State Location
OpenTofu stores each workspace’s state underterraform.tfstate.d/<workspace-name>. For example:
Do not manually edit files in the
terraform.tfstate.d/ directory—always use OpenTofu commands to manage state.5. Review the Configuration Files
Yourproject-sapphire folder should include:
- variables.tf
- provider.tf
variables.tf
- Type of
region? Amap(string). region["india-payroll"]default?"ap-south-1".ami["india-payroll"]default?"ami-55140119877avm".
provider.tf
6. Update main.tf to Invoke the Module
Add a module block in main.tf that points to your shared payroll application:
7. Initialize OpenTofu
Download providers and modules:8. Apply Configuration Across All Workspaces
Deploy the payroll app in each region:-
US Payroll
-
UK Payroll
-
India Payroll
Workspace-State Mapping
| Workspace | AWS Region | AMI ID | State File Location |
|---|---|---|---|
| us-payroll | us-east-1 | ami-24e140119877avm | terraform.tfstate.d/us-payroll/terraform.tfstate |
| uk-payroll | eu-west-2 | ami-351e40119877avm | terraform.tfstate.d/uk-payroll/terraform.tfstate |
| india-payroll | ap-south-1 | ami-55140119877avm | terraform.tfstate.d/india-payroll/terraform.tfstate |