terraform apply in the Project A directory creates the EC2 instance and generates its corresponding state file.
Now, suppose you want to replicate this setup for a new project (Project B) with a different AMI ID and server name. The straightforward approach might involve creating a new directory for Project B, copying Project A’s configuration, and updating the AMI ID and tags. An example configuration combining both projects might look like this:
Terraform workspaces allow you to use one configuration directory to manage multiple projects (or environments) without duplicating files. This improves maintainability and prevents configuration drift.
Using Workspaces to Manage Environments
Terraform workspaces isolate state within the same configuration directory. To create a workspace for Project A, run:Parameterizing Your Configuration for Workspaces
To maintain a single configuration that dynamically adjusts for different projects in theca-central-1 region, create a variables.tf file. This file will define the region, instance type, and a map variable for AMI IDs—differentiating between Project A and Project B.
main.tf) to dynamically select values based on the current workspace. Here, the AMI is chosen using Terraform’s lookup function combined with the terraform.workspace variable, and the instance tag is automatically set to the workspace name:
Switching Workspaces and Applying Configuration Changes
After setting up your configuration files, runterraform plan to preview changes for the current workspace (for example, ProjectA):
terraform plan in the ProjectB workspace, Terraform will use the AMI and tag assigned to Project B:
terraform workspace select command. For example, to switch back to ProjectA:
terraform apply in each workspace, Terraform stores each workspace’s state in a separate subdirectory within the terraform.tfstate.d directory. For example:
Using workspaces ensures that changes in one environment (e.g., ProjectA) do not impact another (e.g., ProjectB), thanks to the isolated state files.