Skip to main content

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?

  1. Purpose of Workspaces:

    • Workspaces help you keep state files separate for different environments, preventing conflicts and accidental changes in the wrong environment.
  2. Default Workspace:

    • Every Terraform configuration has at least one workspace, named default.

Managing Workspaces

  1. Creating a New Workspace:

    • Use terraform workspace new <workspace_name> to create a new workspace.
    • Example: terraform workspace new development
  2. Switching Workspaces:

    • Switch between workspaces with terraform workspace select <workspace_name>.
    • Example: terraform workspace select production
  3. Listing Workspaces:

    • List all existing workspaces with terraform workspace list.
  4. Deleting a Workspace:

    • Delete a workspace (except the default workspace) with terraform workspace delete <workspace_name>.

Using Workspaces in Configuration

  • Use the ${terraform.workspace} interpolation to alter behavior based on the current workspace.
  • Example:
    resource "aws_s3_bucket" "bucket" {
    bucket = "my-app-${terraform.workspace}"
    acl = "private"
    }
    This creates an S3 bucket with a name that includes the workspace name.

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.