DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 12 of 17
Your progress · 0%
On this page
  1. Workspaces
  2. A folder per environment
↖ Course roadmap
Lesson 12 · Environments

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.

25 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
Lab status

Verified 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.

Same code, separate state: switch workspaces, or switch folders.© Diagram: DevOps Academy

Same code, separate state: switch workspaces, or switch folders.© Diagram: DevOps Academy

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 show
  • terraforminfrastructure as code
terraform apply -auto-approve
  • applymake 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.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.

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:

  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

SituationUse
Throwaway environment per pull requestWorkspaces
Personal sandbox copiesWorkspaces
dev, staging and prodA folder per environment
Prod needs different credentials or approvalA 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.

⌘
Mini 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.

Input: main.tf with local_file.config using terraform.workspaceOutput: ~/environments.txt
Reveal 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-approve
  • terraforminfrastructure as code
  • &&run the next command only if this one worked
  • applymake 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 done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

You create workspace prod and run terraform plan for the first time. What does Terraform see?

Go deeper

Official reading for this lesson

  • DocsWorkspacesHashiCorp ↗
  • Docsterraform workspace commandHashiCorp ↗
  • DocsWhen not to use multiple workspacesHashiCorp ↗
  • DocsS3 backend workspace_key_prefixHashiCorp ↗

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.

← PreviousData sources, templates and provisionersNext lesson →Terraform in CI/CD