Skip to main content

Infrastructure as code · Intermediate · 20 min

Use Terraform workspaces for separate environments, and know when not to

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/local 2.9 · hashicorp/random 3.9

You will run one Terraform configuration as separate dev and staging workspaces with per-environment settings, find where each workspace keeps its state, guard every apply with a workspace check, and compare the result with a directory per environment.

On this page

A Terraform workspace is a second (or third, or tenth) state file attached to the same configuration. The code stays the same; terraform workspace select staging points every plan and apply at a different state, so the same files can build a dev copy and a staging copy that never touch each other.

That is useful, and it is also easy to misuse. All workspaces share one backend, one set of credentials and one directory, and the only thing standing between you and an apply to the wrong environment is a word you selected some time ago and may have forgotten.

In this tutorial you build a small configuration with the local and random providers, so nothing touches a cloud account and nothing bills. You will:

  • create dev and staging workspaces and give each its own size and replica count from one lookup map
  • block the default workspace and any misspelt workspace with a precondition
  • find each workspace's state file on disk, and see where the same states would sit in an S3 bucket
  • meet the sharp edges: TF_WORKSPACE, plans that do not name the workspace, and shared credentials
  • add a shell guard that makes you type the workspace name before every apply
  • rebuild the same thing as one directory per environment calling a shared module, and decide which to use

Everything lives in ~/workspaces-demo. Every command works the same in OpenTofu: swap terraform for tofu.

Step 1 · Install Terraform 1.17

Install curl and unzip, then download the Terraform 1.17.2 release for your machine's architecture, check it against HashiCorp's published checksums and put the binary on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

A binary installed this way gets no updates from apt. To upgrade, run the same commands with a newer TF_VERSION.

You will run terraform init in three folders. On prepaid or metered data, set a plugin cache first, so each provider is downloaded once and reused:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints terraform_1.17.2_linux_amd64.zip: OK (or arm64), and terraform version prints Terraform v1.17.2 on its first line.

Step 2 · Write a configuration that reads the workspace name

The configuration describes a pretend app server as local files: a name, a JSON spec with a size, and one file per replica. Inside any configuration, terraform.workspace holds the name of the selected workspace. Use it in names and paths, and use it as the key into a map of per-environment settings:

Bash
mkdir -p ~/workspaces-demo/app
cd ~/workspaces-demo/app

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.9"
    }
  }
}
HCL

cat > settings.tf <<'HCL'
locals {
  # One entry per workspace this configuration may be applied to.
  env_settings = {
    dev     = { size = "small", replicas = 1 }
    staging = { size = "medium", replicas = 2 }
  }

  # Falls back to zero replicas so the plan can reach the guard below.
  settings = lookup(local.env_settings, terraform.workspace, { size = "none", replicas = 0 })
}

# Stops any plan in a workspace that has no settings, including "default".
resource "terraform_data" "workspace_guard" {
  input = terraform.workspace

  lifecycle {
    precondition {
      condition     = contains(keys(local.env_settings), terraform.workspace)
      error_message = "Workspace \"${terraform.workspace}\" has no settings. Run terraform workspace select dev or staging."
    }
  }
}
HCL

cat > main.tf <<'HCL'
resource "random_pet" "server" {
  prefix = terraform.workspace
  length = 2
}

resource "local_file" "spec" {
  filename = "${path.module}/out/${terraform.workspace}/server.json"
  content = jsonencode({
    name     = random_pet.server.id
    size     = local.settings.size
    replicas = local.settings.replicas
  })
}

resource "local_file" "replica" {
  count    = local.settings.replicas
  filename = "${path.module}/out/${terraform.workspace}/replica-${count.index + 1}.txt"
  content  = "${random_pet.server.id} replica ${count.index + 1}\n"
}

output "server_name" {
  value = random_pet.server.id
}

output "size" {
  value = local.settings.size
}
HCL

terraform init
terraform workspace show

lookup takes a fallback, which keeps the expressions valid in a workspace the map does not know. The precondition then turns that unknown workspace into a clear error instead of a quiet plan with zero replicas.

You start in the default workspace, which every configuration has. Try a plan there:

Bash
terraform plan

Check it worked

terraform workspace show prints default. The plan fails with an error headed something like Resource precondition failed, followed by your message, Workspace "default" has no settings. Nothing has been created, and there is no terraform.tfstate file yet.

Step 3 · Create dev and staging workspaces

terraform workspace new creates a workspace and switches to it. Create dev, then plan and apply:

Bash
cd ~/workspaces-demo/app
terraform workspace new dev
terraform plan -out=tfplan
terraform apply tfplan

Now create staging and do the same. The code has not changed; only the selected workspace has:

Bash
terraform workspace new staging
terraform plan -out=tfplan
terraform apply tfplan
terraform workspace list
terraform output

terraform workspace list marks the selected workspace with *. To move between them, use terraform workspace select dev. In scripts, terraform workspace select -or-create dev selects the workspace and creates it first if it does not exist.

Check it worked

The dev apply ends with Resources: 4 added (the guard, the name, the spec and one replica) and the staging apply with Resources: 5 added, because staging has two replicas. terraform workspace list shows default, dev and * staging. terraform output prints a server_name that starts with staging- and size = "medium". cat out/dev/server.json shows "size":"small" and a name starting with dev-.

Step 4 · Find where each workspace keeps its state

With local state, the default workspace would use terraform.tfstate in the project folder. Every other workspace gets its own folder under terraform.tfstate.d:

Bash
cd ~/workspaces-demo/app
find terraform.tfstate.d -name '*.tfstate'
terraform workspace select dev
terraform state list

Each file is a complete, separate state. Deleting terraform.tfstate.d/staging would make Terraform forget every staging object without destroying any of them, so treat that folder as carefully as any state file, and keep it out of Git.

A team keeps state in a remote backend instead. With the S3 backend, a block like this one (replace the bucket name and region with yours) puts each workspace's state at a different key in the same bucket:

HCL
terraform {
  backend "s3" {
    bucket       = "example-team-tf-state" # replace this
    key          = "app/terraform.tfstate"
    region       = "eu-west-1"             # replace this
    use_lockfile = true
  }
}

The default workspace uses the key as written. Every other workspace is stored under the workspace_key_prefix, which defaults to env::

Text
example-team-tf-state/app/terraform.tfstate
example-team-tf-state/env:/dev/app/terraform.tfstate
example-team-tf-state/env:/staging/app/terraform.tfstate

That layout is the first limit of workspaces. All three states sit in one bucket, behind one backend block, read and written with whatever credentials the person running Terraform has. Anyone who can plan dev can also read, and usually overwrite, staging's state. Setting up the bucket itself is covered in /tutorials/terraform-1-17-remote-state-on-s3.

Check it worked

find prints two paths: terraform.tfstate.d/dev/terraform.tfstate and terraform.tfstate.d/staging/terraform.tfstate. After selecting dev, terraform state list shows four addresses, including local_file.replica[0] and no local_file.replica[1].

Step 5 · See how easy it is to hit the wrong workspace

The selected workspace is remembered per folder, in .terraform/environment, long after you have forgotten choosing it. Say you mean to give dev a second replica, but staging is still selected from yesterday. Select staging to set that scene, then change dev's settings:

Bash
cd ~/workspaces-demo/app
terraform workspace select staging
cat > settings.tf <<'HCL'
locals {
  # One entry per workspace this configuration may be applied to.
  env_settings = {
    dev     = { size = "small", replicas = 2 }
    staging = { size = "medium", replicas = 2 }
  }

  # Falls back to zero replicas so the plan can reach the guard below.
  settings = lookup(local.env_settings, terraform.workspace, { size = "none", replicas = 0 })
}

# Stops any plan in a workspace that has no settings, including "default".
resource "terraform_data" "workspace_guard" {
  input = terraform.workspace

  lifecycle {
    precondition {
      condition     = contains(keys(local.env_settings), terraform.workspace)
      error_message = "Workspace \"${terraform.workspace}\" has no settings. Run terraform workspace select dev or staging."
    }
  }
}
HCL
terraform plan

The plan says No changes, and nothing in its output names the workspace. Here the mistake is harmless: you notice dev did not change. The dangerous version is the reverse, where you edit a shared resource, plan in the workspace you think is dev, and apply to staging or production.

A second trap is the TF_WORKSPACE environment variable. CI systems often set it, and it overrides the workspace you selected:

Bash
TF_WORKSPACE=dev terraform workspace show
terraform workspace show

A shell that still has TF_WORKSPACE exported from an earlier session will quietly send every command to that workspace.

Now select dev on purpose and apply the change you meant to make:

Bash
terraform workspace select dev
terraform plan -out=tfplan
terraform apply tfplan

Check it worked

The plan in staging ends with No changes. Your infrastructure matches the configuration. The first terraform workspace show prints dev and the second prints staging. The dev apply ends with Resources: 2 added, 0 changed, 1 destroyed. (the new replica, plus the spec file, which the local provider replaces whenever its content changes), and ls out/dev lists replica-2.txt.

Step 6 · Make every apply show the workspace first

You cannot make the plan output louder, but you can put a check in front of apply. Save this shell function in its own file and load it from ~/.bashrc:

Bash
cat > ~/.tf-guard.sh <<'SH'
# Shows the Terraform workspace and asks you to type it before applying.
tf_apply() {
  local ws answer
  ws=$(terraform workspace show) || return 1
  printf '\nTerraform workspace: %s\n' "$ws" >&2
  if [ -n "${TF_WORKSPACE:-}" ]; then
    printf '(set by TF_WORKSPACE)\n' >&2
  fi
  read -r -p "Type the workspace name to apply to it: " answer
  if [ "$answer" != "$ws" ]; then
    printf 'Cancelled: you typed "%s", the workspace is "%s".\n' "$answer" "$ws" >&2
    return 1
  fi
  terraform apply "$@"
}
SH
echo '[ -f ~/.tf-guard.sh ] && . ~/.tf-guard.sh' >> ~/.bashrc
. ~/.tf-guard.sh

Use tf_apply wherever you used terraform apply; it passes every argument through. Try it from the app folder with dev selected, and type staging at the prompt:

Bash
cd ~/workspaces-demo/app
tf_apply

Run it again and type dev. Terraform then plans and asks its own yes question as usual. Typing a word is a small cost, and it forces you to read which environment you are in at the one moment it matters. It does not stop someone running plain terraform apply, so treat it as a habit for people, not a control. In CI, protect each environment with its own credentials and approval rules instead.

Check it worked

Typing staging prints Cancelled: you typed "staging", the workspace is "dev". and applies nothing. Typing dev reaches Terraform's plan, which reports no changes. In a new terminal, type tf_apply prints the function, so it loads with every shell.

Step 7 · Build the same thing as a directory per environment

The common alternative is one folder per environment, each a small root configuration that calls a shared module. Each folder has its own backend block, so each environment can have its own bucket, its own state permissions and its own credentials. Move the resources into a module and add two thin environment folders:

Bash
mkdir -p ~/workspaces-demo/per-env/modules/server ~/workspaces-demo/per-env/envs/dev ~/workspaces-demo/per-env/envs/staging
cd ~/workspaces-demo/per-env

cat > modules/server/main.tf <<'HCL'
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.9"
    }
  }
}

variable "environment" {
  type = string
}

variable "size" {
  type = string
}

variable "replicas" {
  type = number
}

variable "out_dir" {
  type = string
}

resource "random_pet" "server" {
  prefix = var.environment
  length = 2
}

resource "local_file" "spec" {
  filename = "${var.out_dir}/server.json"
  content = jsonencode({
    name     = random_pet.server.id
    size     = var.size
    replicas = var.replicas
  })
}

resource "local_file" "replica" {
  count    = var.replicas
  filename = "${var.out_dir}/replica-${count.index + 1}.txt"
  content  = "${random_pet.server.id} replica ${count.index + 1}\n"
}

output "server_name" {
  value = random_pet.server.id
}
HCL

cat > envs/dev/main.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"
  # backend "s3" { bucket = "example-dev-tf-state" ... } goes here, one bucket per environment.
}

module "server" {
  source      = "../../modules/server"
  environment = "dev"
  size        = "small"
  replicas    = 2
  out_dir     = "${path.module}/out"
}

output "server_name" {
  value = module.server.server_name
}
HCL

cat > envs/staging/main.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"
  # backend "s3" { bucket = "example-staging-tf-state" ... } goes here, one bucket per environment.
}

module "server" {
  source      = "../../modules/server"
  environment = "staging"
  size        = "medium"
  replicas    = 2
  out_dir     = "${path.module}/out"
}

output "server_name" {
  value = module.server.server_name
}
HCL

terraform -chdir=envs/dev init
terraform -chdir=envs/dev plan -out=tfplan
terraform -chdir=envs/staging init
terraform -chdir=envs/staging plan -out=tfplan

-chdir runs Terraform as if you had cd-ed into that folder. The environment is now part of the path you type, and of the prompt in your terminal if you cd there, so there is nothing hidden to forget.

Compare the two layouts:

  • Workspaces keep one copy of the code and make a new environment one command away. They suit short-lived copies of the same thing: a stack per feature branch, a per-developer sandbox, or a test run that is destroyed afterwards. They do not suit environments that need different credentials, different backends or different approval rules, and HashiCorp's own documentation says so.
  • A directory per environment costs a few duplicated lines per folder, but every difference is written down and reviewable. Dev and production can live in different accounts, and a pull request that touches envs/prod/ is obviously a production change. Most teams use this for long-lived dev, staging and production.

The two also combine: a directory per account or environment, with workspaces inside one of them for throwaway copies.

Check it worked

Each init ends with Terraform has been successfully initialized! Each plan ends with Plan: 4 to add, 0 to change, 0 to destroy. (the name, the spec and two replicas), and the names it shows start with module.server.. Each folder has its own .terraform directory and will get its own terraform.tfstate on apply.

Step 8 · Destroy each workspace and clean up

A workspace that still tracks resources cannot be deleted without -force, and -force would leave those resources running with no state pointing at them. Destroy each workspace first. Plan the destroy and read it before applying:

Bash
cd ~/workspaces-demo/app
terraform workspace select dev
terraform plan -destroy -out=tfplan
terraform apply tfplan
terraform workspace select staging
terraform plan -destroy -out=tfplan
terraform apply tfplan

You cannot delete the workspace you are in, or the default workspace. Switch to default, then delete the two empty ones:

Bash
terraform workspace select default
terraform workspace delete dev
terraform workspace delete staging
terraform workspace list

The next command deletes the whole demo folder, including both layouts and any state. Check you are deleting ~/workspaces-demo and nothing else:

Bash
cd ~
rm -rf ~/workspaces-demo

Keep ~/.tf-guard.sh if you want the guard for your own projects. Otherwise remove it, and delete the tf-guard.sh line from ~/.bashrc:

Bash
rm -f ~/.tf-guard.sh

If you installed Terraform only for this tutorial, remove the binary and the plugin cache, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache

Check it worked

The dev destroy ends with Destroy complete! Resources: 5 destroyed. and the staging one with Resources: 5 destroyed. Each delete prints Deleted workspace "dev". (then "staging"), and terraform workspace list shows only * default. ls ~/workspaces-demo then reports No such file or directory.

Next steps

  • Store each environment's state in S3 with locking in /tutorials/terraform-1-17-remote-state-on-s3.
  • Run the same workflow with OpenTofu in /tutorials/manage-infrastructure-with-opentofu.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.