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.
By the end of this lesson you'll be able to
0 of 4 completeVerified lab: creating, applying and switching workspaces. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: the folder-per-environment layout: explained, not run.
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.
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:
resource "local_file" "config" { filename = "${path.module}/out/${terraform.workspace}.txt" content = "environment: ${terraform.workspace}\n" }
$ 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
terraform workspace showterraforminfrastructure as code
terraform apply -auto-approveapplymake the changes-auto-approveskip the yes prompt
The * marks the current workspace. Both applies created a resource with the same address,
local_file.config, but in different states:
$ ls out/ terraform.tfstate.d/ out/: dev.txt prod.txt terraform.tfstate.d/: dev prod
ls out/ terraform.tfstate.d/lslist files
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.workspacefor 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.
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
# envs/prod/main.tf module "app" { source = "../../modules/app" env = "prod" instance_type = "t3.large" min_size = 3 }
What you get:
- Differences are visible. Prod's size and settings are right there in
envs/prod, reviewed in pull requests, not hidden in a workspace conditional. - 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. - Smaller blast radius. You
cdinto 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 |
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.
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.
~/environments.txtReveal one safe solution
$ 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
terraform workspace new dev && terraform apply -auto-approveterraforminfrastructure as code&&run the next command only if this one workedapplymake the changes-auto-approveskip the yes prompt
{ terraform workspace list; ls terraform.tfstate.d/; ls out/; } > ~/environments.txt>write output to a file, replacing it
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 yourself
0 of 5 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
You create workspace prod and run terraform plan for the first time. What does Terraform see?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.