Terraform workspaces allow you to reuse the same configuration directory for multiple environments by isolating state files.
Listing and Creating Workspaces
Every Terraform configuration automatically creates a workspace named “default.” You can list all workspaces with:terraform workspace new command:
terraform workspace list indicates the current active workspace:
Configuring Different Environments
Assume that both production and development environments will deploy EC2 instances in the “ca-central-1” region with the same AMI. However, production demands a more powerful machine (usingm5.large), while development will use t2.micro. To accommodate this difference, update your configuration to determine the instance type based on the active workspace. Convert the instance_type variable into a map and apply the lookup function.
Updated Configuration
Make the following modifications to your resource block and variables:terraform.workspace returns the name of the current workspace. When used with the lookup function, it selects the appropriate instance type from the map. For instance, in the development workspace it returns “t2.micro,” and in the production workspace it returns “m5.large.”
You can verify this behavior using the Terraform console:
terraform apply in a particular workspace, Terraform selects the corresponding instance type and updates resource tags accordingly. For example, in the development workspace, the plan will show:
Workspace State Files
When using workspaces with local state, Terraform no longer uses a singleterraform.tfstate file in the configuration directory. Instead, it stores each workspace’s state in a dedicated subdirectory within terraform.tfstate.d. For example, the directory structure might look like this:
terraform.tfstate file, ensuring that the state for one environment doesn’t interfere with another.
That concludes our guide on Terraform workspaces. Harness this feature to efficiently manage multiple infrastructure environments with a single configuration.