# Environments: workspaces or folders

Run the same code for dev, staging and prod with separate state, using CLI workspaces or a folder per environment, and know which one to choose for which job.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 12. About 25 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/12-environments

## What you will learn

- Explain why each environment needs its own state
- Create, list and switch workspaces, and use terraform.workspace in code
- Lay out a folder per environment that calls shared modules
- Choose between workspaces and folders, and know their failure modes

> **Lab status.** **Verified lab:** creating, applying and switching workspaces. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the folder-per-environment layout: explained, not run. <br />**Cloud lab:** none; nothing here needs a cloud account.

Dev, staging and prod should be built from the same code, so what you test is what you ship. But
each needs its **own state**: applying dev must never touch prod. Terraform offers two ways to get
that, and teams argue about them a lot. This lesson shows both, with real output, and when to pick
which.

> **Figure.** Left, workspaces: one folder with several states. terraform workspace new dev and select prod; states stored under terraform.tfstate.d/dev and prod; names use terraform.workspace. Pros: quick, no copying. Cons: same backend and access for all, and which-workspace-am-I-in mistakes. Right, folder per environment: shared code in modules/app, envs/dev/main.tf calls the module with dev.tfvars, envs/prod has its own tfvars and backend.tf with its own bucket and key. Pros: differences are visible in code review, prod can have its own account and access. Con: a little repetition.
>
> Same code, separate state: switch workspaces, or switch folders.

## Workspaces

A **workspace** is a named state within one configuration. Every project starts in `default`. The
lab used one tiny file that includes the workspace name:

```hcl
resource "local_file" "config" {
  filename = "${path.module}/out/${terraform.workspace}.txt"
  content  = "environment: ${terraform.workspace}\n"
}
```

```text
$ terraform workspace show
default
$ terraform workspace new dev
Created and switched to workspace "dev"!

You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
$ terraform apply -auto-approve
...
  # local_file.config will be created
  + resource "local_file" "config" {
      + content              = <<-EOT
            environment: dev
        EOT
      + filename             = "./out/dev.txt"
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ terraform workspace new prod
Created and switched to workspace "prod"!
...
$ terraform apply -auto-approve
...
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ terraform workspace list
  default
  dev
* prod
```

The `*` marks the current workspace. Both applies created a resource with the same address,
`local_file.config`, but in different states:

```text
$ ls out/ terraform.tfstate.d/
out/:
dev.txt
prod.txt

terraform.tfstate.d/:
dev
prod
```

With the local backend, each workspace's state lives in `terraform.tfstate.d/<name>/`. With S3,
Terraform stores them under a prefix in the same bucket (`env:/<workspace>/<key>` by default, set by
`workspace_key_prefix`). In code, `terraform.workspace` is the current name, often used in names and
in lookups like `lookup(var.sizes, terraform.workspace)`.

Switch with `terraform workspace select dev`. Delete one with `terraform workspace delete prod`,
which refuses while its state still has resources.

### Where workspaces fit and where they don't

Workspaces are great for **short-lived copies**: a test environment per feature branch, created and
destroyed by CI. HashiCorp's own docs warn against relying on them for long-lived environments that
need different credentials or access, because:

- Every workspace uses the **same backend and credentials**, so whoever can apply dev can apply prod.
- The code must branch on `terraform.workspace` for every difference, which gets hard to read.
- Nothing on screen tells you which workspace you're in, except `terraform workspace show`. Applying
  in the wrong one is a classic mistake.

## A folder per environment

The alternative: one folder per environment, each a small root module that calls shared modules.

```text
infra/
├── modules/
│   └── app/                 # the real logic, written once
└── envs/
    ├── dev/
    │   ├── main.tf          # module "app" { source = "../../modules/app" ... }
    │   ├── backend.tf       # key = "shop/dev/terraform.tfstate"
    │   └── dev.tfvars
    └── prod/
        ├── main.tf
        ├── backend.tf       # key = "shop/prod/terraform.tfstate", maybe a different account
        └── prod.tfvars
```

```hcl
# envs/prod/main.tf
module "app" {
  source        = "../../modules/app"
  env           = "prod"
  instance_type = "t3.large"
  min_size      = 3
}
```

What you get:

1. **Differences are visible.** Prod's size and settings are right there in `envs/prod`, reviewed in
   pull requests, not hidden in a workspace conditional.
2. **Separate backends and credentials.** Prod's state can live in a different bucket, even a
   different AWS account, and CI can require approval only for `envs/prod`.
3. **Smaller blast radius.** You `cd` into a folder to act on it, so applying to prod is a deliberate
   step.

The cost is a little repetition: each folder has its own `main.tf` and backend file. Tools like
Terragrunt (lesson 15) exist to remove it.

### Choosing

| Situation                                    | Use                                                  |
| -------------------------------------------- | ---------------------------------------------------- |
| Throwaway environment per pull request       | Workspaces                                           |
| Personal sandbox copies                      | Workspaces                                           |
| dev, staging and prod                        | A folder per environment                             |
| Prod needs different credentials or approval | A folder per environment, ideally a separate account |

> **In production.** Put production in its own cloud account with its own state bucket, and let only the pipeline apply there. Whichever layout you use, print the environment in the plan (an output like `env = "prod"`) so reviewers always know what they're approving.

## Mission: Create dev and prod with workspaces, then plan the folder layout

Using the workspace example, create dev and prod workspaces, apply in both, and record terraform workspace list and the state folders. Then write the folder-per-environment tree you'd use for a real dev and prod, with the backend key for each.

- You need: main.tf with local_file.config using terraform.workspace
- You'll have: ~/environments.txt

```sh
$ terraform workspace new dev && terraform apply -auto-approve
$ terraform workspace new prod && terraform apply -auto-approve
$ { terraform workspace list; ls terraform.tfstate.d/; ls out/; } > ~/environments.txt
```

You should see `dev.txt` and `prod.txt` in `out/`, two folders under `terraform.tfstate.d/`, and a
`*` next to the workspace you're in. Finish by adding your `envs/dev` and `envs/prod` tree to the
file.

## Try it

- Run `terraform workspace new dev` and `terraform workspace new prod`, applying in each.
- Run `terraform workspace list` and find where each state file lives.
- Use `terraform.workspace` in a file name and see each workspace create its own file.
- Sketch an `envs/dev` and `envs/prod` layout that calls one shared module.
- Do the mini mission and keep `~/environments.txt`.

## Quiz

1. You create workspace prod and run terraform plan for the first time. What does Terraform see?
   - Everything from the default workspace
   - **An empty state; it plans to create everything for prod** (answer)
   - An error
   Why: Each workspace has its own state. A new workspace starts empty, even though the code is the same.

2. What is the main risk of using workspaces for dev and prod?
   - They're slower
   - **Same code, backend and credentials for every environment, and it's easy to apply in the wrong workspace** (answer)
   - They don't support variables
   Why: The only thing separating environments is the selected workspace. A folder per environment (or a separate account) makes the difference visible and controllable.

3. In a folder-per-environment layout, how do environments share code?
   - By copying main.tf
   - **Each environment folder calls the same modules with its own values and backend** (answer)
   - Through workspaces
   Why: Shared modules hold the logic; envs/dev and envs/prod differ only in inputs, backend and permissions.

## Resources

- [Workspaces](https://developer.hashicorp.com/terraform/language/state/workspaces) (HashiCorp)
- [terraform workspace command](https://developer.hashicorp.com/terraform/cli/commands/workspace) (HashiCorp)
- [When not to use multiple workspaces](https://developer.hashicorp.com/terraform/cli/workspaces#when-not-to-use-multiple-workspaces) (HashiCorp)
- [S3 backend workspace_key_prefix](https://developer.hashicorp.com/terraform/language/backend/s3#workspace_key_prefix) (HashiCorp)
