# Terraform workflow: migrate from workspaces to directory-per-environment

## When

`terraform workspace select` nearly (or actually) applied dev config to prod state. The team wants hard separation: different backends, different credentials, no shared mutable selector.

## Steps

1. Create the directory structure: `envs/dev`, `envs/staging`, `envs/prod`, each a root module calling the shared child modules. Extract the shared config into modules first if it is not already modular.
2. Per environment: copy the workspace's state to the new backend key. Procedure per env: `terraform workspace select [env]`, `terraform state pull > backup-[env].json`, configure the new directory's backend, `terraform init -migrate-state` answering with the backed-up state.
3. Verify per env: `terraform plan` in the new directory must be clean against that env's state. Do this for dev first, then staging, then prod.
4. Retarget CI: one job per directory, each with its own credentials and backend config. Delete the workspace-selection logic from the pipeline.
5. Only after all envs verify: remove the old workspace states (`terraform workspace delete` after selecting each, with the new dirs confirmed working).

## Rules for agents

1. One environment per session, lowest first. The prod migration happens last and gets the most review.
2. Keep the shared modules identical across envs during migration. Refactoring modules AND migrating layout in one change is two risks multiplied.
3. Different credentials per environment is the point of the exercise. If prod and dev still share credentials after migration, you moved deck chairs.
4. After migration, `terraform workspace` commands should have no workspaces left with real state. Verify; leftover workspaces are confusion waiting to happen.
