Workspaces
Terraform workspaces allow you to manage multiple distinct sets of Terraform state within the same configuration. This is particularly useful for managing different environments (like development, staging, and production) or variations of your infrastructure.
What are Terraform Workspaces?
-
Purpose of Workspaces:
- Workspaces help you keep state files separate for different environments, preventing conflicts and accidental changes in the wrong environment.
-
Default Workspace:
- Every Terraform configuration has at least one workspace, named
default.
- Every Terraform configuration has at least one workspace, named
Managing Workspaces
-
Creating a New Workspace:
- Use
terraform workspace new <workspace_name>to create a new workspace. - Example:
terraform workspace new development
- Use
-
Switching Workspaces:
- Switch between workspaces with
terraform workspace select <workspace_name>. - Example:
terraform workspace select production
- Switch between workspaces with
-
Listing Workspaces:
- List all existing workspaces with
terraform workspace list.
- List all existing workspaces with
-
Deleting a Workspace:
- Delete a workspace (except the
defaultworkspace) withterraform workspace delete <workspace_name>.
- Delete a workspace (except the
Using Workspaces in Configuration
- Use the
${terraform.workspace}interpolation to alter behavior based on the current workspace. - Example:
This creates an S3 bucket with a name that includes the workspace name.
resource "aws_s3_bucket" "bucket" {
bucket = "my-app-${terraform.workspace}"
acl = "private"
}
Best Practices
- Environment Separation: Use different workspaces for different environments. This keeps your environments isolated and reduces the risk of changes affecting the wrong environment.
- Consistent Naming: Use consistent and descriptive naming conventions for workspaces.
- Caution with State Files: Be cautious when switching workspaces, as each workspace has its own state file.