Workspaces
Terraform workspaces provide a mechanism to manage multiple environments (e.g., dev, staging, prod) by isolating state data and configuration contexts. This ensures parallel runs for different environments do not interfere with each other, reducing the risk of accidental resource conflicts or unintended changes. Workspaces are particularly useful for teams managing infrastructure across development, testing, and production stages.
Creating and Managing Workspaces¶
Workspaces are created using the terraform workspace new command. Each workspace maintains its own state file and configuration context, allowing independent management of resources.
Example: Creating workspaces for dev and staging
# Create a 'dev' workspace
terraform workspace new dev
# Create a 'staging' workspace
terraform workspace new staging
Switching between workspaces
Workspaces are automatically saved in the backend configuration (e.g., local file or remote storage), ensuring state isolation even across team members or CI/CD pipelines.
Using Workspaces for Environment-Specific Configurations¶
Workspaces enable environment-specific configurations by isolating state data. For example, a single Terraform configuration can manage resources for dev and staging by switching workspaces during apply.
Example: Applying to the dev workspace
# Ensure you're in the 'dev' workspace
terraform workspace select dev
# Apply configuration
terraform apply
Example: Applying to the staging workspace
# Switch to the 'staging' workspace
terraform workspace select staging
# Apply configuration
terraform apply
Each workspace stores its state separately, ensuring resources in dev (e.g., test servers) do not interfere with staging (e.g., pre-production servers).
Best Practices for Workspace Isolation¶
- Use descriptive names: Align workspace names with environment labels (e.g.,
dev,prod). - Avoid default workspace for production: Use explicit workspaces for production to prevent accidental changes.
- Lock state files: Enable state locking to prevent concurrent modifications to state files.
- Consistent backend configuration: Ensure all workspaces use the same backend (e.g., remote storage) for centralized state management.
By leveraging workspaces, teams can enforce strict environment isolation, reduce operational risks, and streamline CI/CD workflows for infrastructure as code.
Key takeaways¶
- Workspaces isolate state data and configuration contexts for different environments.
- Use
terraform workspace newandterraform workspace selectto manage environments. - Apply configurations to specific workspaces to avoid resource conflicts.
- Follow naming conventions and state locking best practices for production-grade workflows.
- Ensure consistent backend configuration across all workspaces for reliable state management.