Module 5 ended with EcoMarket deployed across three clouds and a promise: to come back to the language with everything the real cloud had made necessary. The first debt on that list is the oldest in the course. Ever since module 3, every time the word workspace appeared we parked it with a footnote: "covered in 06-01". And ever since module 4, EcoMarket has been separating its environments with directories and .tfvars files without ever justifying why it does not use the mechanism Terraform itself ships for exactly that.

This lesson settles that debt in full. You are going to see what a CLI workspace actually is — several states for one configuration and one backend — where each state file ends up in S3 and on disk, which commands govern it, and which patterns terraform.workspace enables. Then comes the uncomfortable part: what workspaces do not solve, which is why most serious platform teams rule them out for separating dev from prod. And finally, the cases where they are exactly the right tool, which do exist and are more numerous than the mechanism's reputation suggests: ephemeral environments per pull request, identical replicas per region or per customer, labs.

The practical conclusion is not "workspaces are bad". It is that they solve one very specific problem — the same code deployed several times — and that separating environments is almost never that problem, because environments diverge.

  1. What a CLI workspace is

A workspace is an additional state attached to one configuration and one backend. Nothing more. That short sentence contains the three things worth remembering:

  • One configuration. The same .tf files, the same directory, the same modules, the same provider versions.
  • One backend. The same bucket, the same lock table, the same credentials for reaching the state.
  • Several states. Terraform keeps one per workspace and uses the one belonging to the active workspace.

Every configuration has at least one workspace, called default, even if you have never run terraform workspace. If you have got through five modules of this course without touching the subject, you have been working in default the whole time.

flowchart TD
    C["Configuration<br/>infra/app/*.tf<br/>ONE only"] --> B["S3 backend<br/>ONE only<br/>bucket + lock table"]
    B --> E1["State: default"]
    B --> E2["State: staging"]
    B --> E3["State: prod"]
    E1 --> R1["Resources<br/>of default"]
    E2 --> R2["Resources<br/>of staging"]
    E3 --> R3["Resources<br/>of prod"]

What matters in the diagram is what does not branch: the configuration and the backend are single. If prod needs a resource that staging does not have, that resource sits in the same .tf file that staging reads, and it can only disappear for staging through a conditional. Hold on to that idea: it is the axis of section 5.

What a workspace is and is not

Claim True? Nuance
Separates states Yes It is literally its only function
Separates configurations No The code is the same for all of them
Separates credentials No The provider's are resolved identically in all of them
Separates backends No A workspace cannot live in another bucket
Separates permissions No Whoever can apply in one can apply in all
Isolates locking Yes Each state is locked separately
Costs money No It is one more object in the bucket
Exists in every backend Almost local, s3, gcs, azurerm, consul, kubernetes, remote yes; some third-party ones no

That table is the honest summary of the mechanism. Four "no"s in a row on the rows that matter most for separating environments.

  1. Where each workspace's state lives

This is where the mechanism becomes concrete, and where the first unpleasant surprise appears for anyone who has configured a backend by hand as we did in 03-03.

Local backend

With the local backend (no backend block), the default workspace stores its state where it always has: terraform.tfstate in the working directory. The other workspaces go into a subdirectory:

infra/app/
├── main.tf
├── terraform.tfstate              # ← workspace "default"
└── terraform.tfstate.d/
    ├── staging/
    │   └── terraform.tfstate      # ← workspace "staging"
    └── prod/
        └── terraform.tfstate      # ← workspace "prod"

The terraform.tfstate.d/ directory must be in .gitignore, exactly like terraform.tfstate. It contains complete states, with their sensitive values inside, and pushing them to the repository is the same mistake you already know from module 3, multiplied by the number of workspaces.

S3 backend

With S3 the rule is different and less intuitive. The key you configured is kept as is for the default workspace, and for the others a prefix is prepended:

<workspace_key_prefix>/<workspace_name>/<key>

The default value of workspace_key_prefix is the string env:. With EcoMarket's configuration:

# infra/app/backend.tf
terraform {
  backend "s3" {
    bucket         = "ecomarket-tfstate-123456789012"
    key            = "ecomarket/dev/app/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "ecomarket-tfstate-locks"
    encrypt        = true
  }
}

The objects end up like this:

flowchart TD
    B["Bucket: ecomarket-tfstate-123456789012"]
    B --> D["ecomarket/dev/app/terraform.tfstate<br/><i>workspace: default</i>"]
    B --> S["env:/staging/ecomarket/dev/app/terraform.tfstate<br/><i>workspace: staging</i>"]
    B --> P["env:/prod/ecomarket/dev/app/terraform.tfstate<br/><i>workspace: prod</i>"]

Read the last two keys twice. The dev segment is still there. The prod workspace's state lives at a path containing the word dev, because key was a fixed string that already had the environment inside it and the workspace prefix is prepended, not substituted.

This is not a Terraform bug: it is the consequence of mixing two separation mechanisms. If you are going to use workspaces, the key must not contain the environment name:

terraform {
  backend "s3" {
    bucket = "ecomarket-tfstate-123456789012"
    key    = "ecomarket/app/terraform.tfstate"   # ← no environment in the path
    region = "eu-west-1"
    # workspace_key_prefix = "environments"      # ← optional, replaces "env:"
    use_lockfile = true
  }
}

With workspace_key_prefix = "environments", the keys become environments/staging/ecomarket/app/terraform.tfstate, which at least can be written into an IAM policy without fighting the colon.

Operational warning. The env: prefix contains a : character. It is valid in S3 but awkward in URLs, in IAM policies with wildcards and in some command-line clients, where it has to be escaped or quoted. If you adopt workspaces from the start, change workspace_key_prefix to something without odd characters.

The other backends

Backend State of default State of <ws>
local terraform.tfstate terraform.tfstate.d/<ws>/terraform.tfstate
s3 <key> <workspace_key_prefix>/<ws>/<key>
gcs <prefix>/default.tfstate <prefix>/<ws>.tfstate
azurerm <key> <key>env:<ws>
kubernetes secret tfstate-default-<suffix> secret tfstate-<ws>-<suffix>
remote (HCP) does not apply the same way see section 10

GCS is the only one whose scheme is reasonable to read, because its configuration uses prefix rather than a complete key — which is why in 03-03 we noted that the object ended up at .../default.tfstate. Azure concatenates without a separator, so the prod key is ecomarket/app/terraform.tfstateenv:prod, which is exactly as ugly as it looks.

  1. The commands

There are five of them, and they fit on one screen. They all operate on the already initialised backend, so terraform init always comes first.

terraform workspace list

$ terraform workspace list
  default
* staging
  prod

The asterisk marks the active workspace. The list comes from the backend, not from a local file: if a colleague created prod from their machine, it shows up on yours after init.

terraform workspace show

$ terraform workspace show
staging

A single line, with no decoration, designed for scripts. It is the one you will use in your shell prompt (section 11) and in the pipeline.

terraform workspace new

$ terraform workspace new pr-482
Created and switched to workspace "pr-482"!

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.

Three details that matter:

  • It creates and selects in a single step. There is no need to select afterwards.
  • The state is born empty. An immediate plan proposes creating everything.
  • It accepts -state=path.tfstate to seed the new workspace with an existing state. That is the migration route: copying default's state into a workspace with a proper name.
# Migrate the current state of "default" into a workspace called "prod"
terraform state pull > /tmp/current-state.tfstate
terraform workspace new -state=/tmp/current-state.tfstate prod
terraform plan          # must come out empty: same resources, different state

After verifying the zero-change plan, what remains is emptying default, which is a delicate operation and only worth doing if you really are going to adopt workspaces.

terraform workspace select

$ terraform workspace select prod
Switched to workspace "prod".

$ terraform workspace select nonexistent
╷
│ Error: Workspace "nonexistent" doesn't exist.
│
│ You can create this workspace with the "new" subcommand
│ or include the "-or-create" flag with the "select" subcommand.
╵

Since Terraform 1.4 there is -or-create, which is what automation uses so that it does not have to distinguish the first run from later ones:

terraform workspace select -or-create=true "pr-${PR_NUMBER}"

terraform workspace delete

$ terraform workspace delete pr-482
╷
│ Error: Workspace is not empty
│
│ Workspace "pr-482" is currently tracking the following resource instances:
│   - module.app.aws_lb.main
│   - module.network.aws_vpc.main
│
│ Deleting this workspace would cause Terraform to lose track of any
│ associated remote objects, which would then require you to delete them
│ manually outside of Terraform.
╵

Deleting a workspace does not destroy its infrastructure: it deletes the state. Terraform refuses if the state is not empty, and rightly so, because what would be left is orphaned infrastructure billing away on its own. The correct order is always:

terraform workspace select pr-482
terraform destroy -auto-approve      # 1. destroy the infrastructure
terraform workspace select default   # 2. leave the workspace
terraform workspace delete pr-482    # 3. now yes, delete the empty state

There is a -force flag, which deletes the state even if it has resources inside. It is the number-one generator of orphaned infrastructure. Use it only once you have verified in the console that the resources no longer exist.

Two other rules about delete: you cannot delete default and you cannot delete the active workspace. Hence step 2 in the block above.

The TF_WORKSPACE environment variable

TF_WORKSPACE=staging terraform plan

This selects the workspace without changing the local selection state. In automation it is preferable to select, because it leaves no trace in .terraform/environment and because its scope is a single command. Its trap: if TF_WORKSPACE is exported in your shell and you forget about it, every command in that session goes to that workspace, including the destroy you thought you were running somewhere else.

Where Terraform remembers the selected workspace

In .terraform/environment, a text file with a single line. It is not in the repository (.terraform/ goes in .gitignore), which means that the workspace selection is local to your machine and is not shared. Two people on the same team, with the same repository, can be in different workspaces without knowing it. Hold on to this fact: it is the root of the risk in section 5.

  1. terraform.workspace and the patterns it enables

terraform.workspace is a read-only value holding the name of the active workspace. We already mentioned it in 02-01 when listing the language's values; here it is time to see what you do with it.

Pattern 1: a suffix in names

locals {
  prefix = "${var.project}-${terraform.workspace}"
}

resource "aws_s3_bucket" "images" {
  bucket = "${local.prefix}-images-${random_pet.suffix.id}"
}

This is the most common use and the most harmless: it avoids name collisions between workspaces that share an account. Notice that it replaces var.environment, and that has a consequence: the environment name stops being a reviewable input in a .tfvars file and comes to depend on an invisible piece of state in your terminal.

Pattern 2: a sizing map keyed by workspace

locals {
  sizing = {
    default = { web_class = "t3.micro",  instances = 1, multi_az = false }
    staging = { web_class = "t3.small",  instances = 2, multi_az = false }
    prod    = { web_class = "m6i.large", instances = 6, multi_az = true  }
  }

  # lookup with a default value: a new workspace does not blow up the plan
  current = lookup(local.sizing, terraform.workspace, local.sizing["default"])
}

module "app" {
  source    = "ecomarket/ecomarket-app/aws"
  version   = "~> 3.0"
  web_class = local.current.web_class
  instances = local.current.instances
  # ...
}

Compare it with what EcoMarket has been doing since module 4: a var.environments of type map(object(...)) fed by .tfvars plus local.current = var.environments[var.environment]. The shape of the data is identical. The only thing that changes is where the key comes from: an input variable or terraform.workspace. That equivalence is the clue that the debate is not about expressiveness, but about governance.

The lookup with a third argument is mandatory in this pattern. Without it, creating a pr-482 workspace makes the plan fail with an Invalid index — an error that does not say "you are missing an entry in the map", but something far more opaque.

Pattern 3: an environment conditional

resource "aws_db_instance" "main" {
  # ...
  multi_az                = terraform.workspace == "prod"
  deletion_protection     = terraform.workspace == "prod"
  backup_retention_period = terraform.workspace == "prod" ? 30 : 1
  skip_final_snapshot     = terraform.workspace != "prod"
}

It works, and it is where the trouble starts. A stray terraform.workspace == "prod" deep inside a module is a time bomb: the module stops being reusable (it depends on what the consumer happens to call their workspace) and the environment logic scatters across the tree instead of living in the module's interface. The rule you already learned in 04-02 still holds: a module must not know which environment it is in; it receives its parameters. If you need terraform.workspace inside a reusable module, what is missing is a variable.

Pattern 4: conditional resources per workspace

# Read replica in production only
resource "aws_db_instance" "replica" {
  count = terraform.workspace == "prod" ? 1 : 0
  # ...
}

Here we are already in hostile territory. The conditional count turns the resource address into an indexed one (aws_db_instance.replica[0]), forces you to guard every reference with one() or try(), and produces code where reading the .tf does not tell you what is deployed: it depends on the invisible variable. Multiply this by fifteen resources that only exist in prod and you have a configuration nobody dares to touch.

  1. The six problems workspaces do not solve

This is the section that justifies EcoMarket's decision. These are not aesthetic objections: each one has a concrete operational consequence.

5.1 One single configuration for every environment

This is the limitation from which nearly all the others follow. If prod needs a read replica, a second load balancer in another region or a message queue that dev does not have, that difference can only be expressed with conditionals inside the shared code. There is no way to have a prod-extra.tf file that dev does not read.

In practice, the differences between environments are not only about size. They start out that way — t3.micro versus m6i.large — and end up structural: prod has a WAF, dev does not; prod has three zones, dev has one; prod replicates the bucket to another region, dev does not even consider it. Each of those differences adds a conditional, and conditionals pile up without anybody ever removing them.

5.2 The same credentials and the same account

A workspace cannot have a different provider from another. The provider configuration is part of the shared code, and credential resolution happens identically in every workspace. This can be read two ways:

  • If your environments are in separate accounts (which is the practice recommended by AWS, Azure and GCP, and what EcoMarket does: 123456789012 for dev, ...13 for staging, ...14 for prod), you would have to select the account with conditionals on terraform.workspace in the provider block, with a variable assume_role. It can be done, it is fragile, and it means your working credentials have access to all three accounts at once.
  • If they are not, you have a bigger problem than workspaces.

And the backend does not change either: every state lives in the same bucket and is locked with the same table. The production state, with its sensitive attributes, is readable by anyone who can read the development state.

5.3 The risk of applying in the wrong workspace

This is the one that produces real incidents. The active workspace is:

  • Invisible: nothing in the output of terraform plan announces it in large letters.
  • Persistent: once selected, it is still selected tomorrow.
  • Local: it is not in the repository, so code review never sees it.

The sequence of the accident is always the same: somebody debugs something in prod, closes the laptop, comes back the next day, edits a variable while thinking about dev and runs terraform apply. The configuration is the same, the directory is the same, the shell prompt is the same. The only difference is one line in a hidden file.

Compare it with the directory alternative: to apply in production you have to physically be in infra/prod/ and, in EcoMarket's case, pass -var-file=prod.tfvars. That is two visible signals versus zero.

5.4 Differences grow over time

A configuration shared between environments starts clean and degrades. The mechanism is well known:

  1. Month 1: the environments are identical except in size. A sizing map is enough.
  2. Month 4: production needs something the others do not. The first count = terraform.workspace == "prod" ? 1 : 0 appears.
  3. Month 9: there are six conditionals. Nobody knows any more which resources exist in staging without running a plan.
  4. Month 14: somebody needs to try a large change in dev and cannot, because touching the shared file means touching production.

Point 4 is the decisive one: a shared configuration couples the pace of change of every environment. A development environment exists precisely so that you can break it without fear, and with workspaces breaking dev requires editing the very file prod depends on.

5.5 You cannot grant different permissions per environment

With workspaces there is no way to say "this team can apply in staging but not in prod". The control would have to sit in the provider credentials, which are the same; in access to the state bucket, which is the same; or in the pipeline, which runs the same directory.

With separate directories, by contrast, everything you already know about permissions applies without inventing anything: path-based owner rules in the repository, protected environments in the pipeline with mandatory review for infra/prod/, different IAM roles per directory. Separation by directory lines up with the control mechanisms that already exist; separation by workspace lines up with none of them.

5.6 Provider and module versions are single

The .terraform.lock.hcl file is one per directory, not one per workspace. And module versions are written into the shared code. The consequence: you cannot upgrade the AWS provider in dev, live with it for two weeks and then upgrade it in prod. When you upgrade it, you upgrade it for everybody, and the next apply in production will run with a provider nobody has exercised there.

This limitation is the one that most surprises people coming from other ecosystems, and it is on its own a sufficient reason to rule out workspaces as an environment separator on a platform with real production. Controlled version progression — dev, then staging, then prod — is exactly what this model prevents.

  1. Why EcoMarket chose separate directories and .tfvars

With the six points above on the table, the decision you have been living with since module 4 explains itself. Let us recall the structure:

ecomarket-infra/
├── modules/
│   ├── network/
│   ├── data/
│   └── app/
└── infra/
    ├── common.auto.tfvars      # what the three environments share
    ├── dev.tfvars
    ├── staging.tfvars
    ├── prod.tfvars
    └── app/
        ├── main.tf
        ├── variables.tf
        ├── backend.tf
        └── guards.tf

And the concrete decisions, with their reasons:

EcoMarket's decision Which problem from section 5 it avoids
One backend.tf per environment with key ecomarket/<environment>/<component>/terraform.tfstate 5.2: states separable by bucket policy
var.environment as an explicit variable, not terraform.workspace 5.3: the environment is written on the command line, is visible in the pipeline and is reviewed in the pull request
var.environments of type map(object(...)) + local.current 5.1: sizing differences live in data, not in conditionals
Version-controlled dev|staging|prod.tfvars files 5.4: the difference between environments is a readable diff of two files
common.auto.tfvars loaded automatically Avoids repeating what does not change, without mixing it with what does
A check guard for the expected AWS account 5.3: if the environment and the credentials do not match, it warns before the apply
Separate accounts per environment 5.2 and 5.5: real isolation comes from the account, not from the state

There is an honest nuance worth saying out loud: EcoMarket uses one single configuration directory with several variable files and several backends, not a complete directory per environment with the code duplicated. It is the middle ground. Structural differences — as opposed to size differences — would be solved with a directory of their own, and when the number of environments grows to the point where repeating backend.tf becomes unsustainable, the answer is Terragrunt, which you will see in 07-05. Directory organisation in depth, with its variants and its trade-offs, is the subject of 07-01.

What is categorical is the other point: EcoMarket's environment never comes out of terraform.workspace. It comes from a variable somebody writes, that appears in the command, that is reviewed in the pull request and that the pipeline sets explicitly.

  1. Four separation strategies, compared

Criterion CLI workspaces Directory per environment Separate repositories Terragrunt (07-05)
Credential isolation None: the same credentials for everything High: each directory with its profile/role Total: different repository and credentials High: each terragrunt.hcl sets its role
State isolation Yes, but the same bucket and the same table Yes, with a bucket or key per environment Total Yes, with keys generated by convention
Configuration divergence Impossible without conditionals Natural: each directory evolves Total, even undesirably so Controlled: shared module + per-environment input
Code duplication None Medium: the scaffolding is repeated High: everything is repeated Low: it is its whole reason for existing
Risk of human error High: the workspace is invisible Low: the path is visible Very low Low: run-all is the residual risk
Different permissions per environment No Yes (path owners, protected environments) Yes, trivially Yes
Provider versions per environment No: a single lock Yes: one lock per directory Yes Yes
Maintenance cost Very low at first, high later Medium and stable High: changes have to be replicated N times Low after the learning curve
Fit with CI/CD Poor: you have to select a workspace and trust Good: one job per directory Good: one pipeline per repository Good, with dependencies resolved
External tooling No No No Yes: a third-party dependency
Ephemeral environments Excellent Poor: creating directories on the fly Unworkable Good
What it is genuinely for Replicas of the same code Environments that diverge Strong organisational isolation Many environments with little duplication

The two rows in bold are why workspaces are ruled out for environments, and the last row is why they are not ruled out entirely.

  1. When workspaces really are the right tool

The criterion is a single question: are the instances I want to separate the same code, today and a year from now? If the answer is a sincere yes, workspaces are the cheapest mechanism there is. These are the three clear cases.

Case A: ephemeral environments per branch or per pull request

An environment that lives three days and is then destroyed has no time to diverge. It is born from the same code the branch proposes, it is tested and it dies. It is the canonical case and we develop it in full in section 9.

Case B: identical replicas per region or per customer

EcoMarket opens in Portugal. The platform in eu-west-3 is exactly the same as the one in eu-west-1, with a different region and different CIDRs:

locals {
  regions = {
    ireland = { region = "eu-west-1", cidr = "10.20.0.0/16", domain = "ecomarket.example.com"    }
    paris   = { region = "eu-west-3", cidr = "10.30.0.0/16", domain = "fr.ecomarket.example.com" }
    milan   = { region = "eu-south-1", cidr = "10.40.0.0/16", domain = "it.ecomarket.example.com" }
  }

  current_region = local.regions[terraform.workspace]
}

provider "aws" {
  region = local.current_region.region

  default_tags {
    tags = {
      Project     = "ecomarket"
      Environment = "prod"
      Region      = terraform.workspace
      ManagedBy   = "terraform"
    }
  }
}

Here terraform.workspace in the provider is not a bomb: it is the axis of the design. The three regions are the same platform and they must stay identical; having the code force them to be so is an advantage, not a limitation. And staged rollout is done by applying workspace by workspace.

The same reasoning holds for a multi-customer platform where each customer gets an isolated copy of the same infrastructure. One workspace per customer, a map with their parameters, and the structural guarantee that nobody adds a piece for one customer without adding it for all of them.

Careful with case B. It works as long as the replicas really are identical. The day Milan needs a resource the others do not have, you are in section 5.1. The alarm signal is the first count = terraform.workspace == "milan" ? 1 : 0.

Case C: personal labs

Every member of the platform team wants their own copy to break things in:

terraform workspace new "lab-${USER}"
terraform apply -var-file=dev.tfvars

None of the objections in section 5 weigh anything here: there is no production, permissions are the same for everybody by definition, divergence does not matter because the lab gets destroyed, and the risk of applying in the wrong workspace is the risk of breaking your own lab.

  1. An ephemeral environment per pull request: EcoMarket's complete case

EcoMarket wants every pull request in the application repository to bring up a complete copy of the platform, test it and destroy it when the request closes. This is the implementation, with the decisions explained.

The configuration

# infra/ephemeral/variables.tf

variable "project" {
  type    = string
  default = "ecomarket"
}

variable "pr_number" {
  description = "Number of the pull request. Injected by the pipeline."
  type        = number

  validation {
    condition     = var.pr_number > 0 && var.pr_number < 100000
    error_message = "The pull request number must be a reasonable positive integer."
  }
}

variable "ttl_hours" {
  description = "Hours of life before the sweeper destroys the environment."
  type        = number
  default     = 48
}
# infra/ephemeral/main.tf

locals {
  # The workspace IS the identifier of the ephemeral environment.
  environment_name = terraform.workspace
  is_ephemeral     = startswith(terraform.workspace, "pr-")
  prefix           = "${var.project}-${local.environment_name}"

  common_tags = {
    Project     = var.project
    Environment = local.environment_name
    ManagedBy   = "terraform"
    Ephemeral   = tostring(local.is_ephemeral)
    # Timestamp for the sweeper. Fixed ONCE, at creation time.
    ExpiresAt   = timeadd(time_static.creation.rfc3339, "${var.ttl_hours}h")
    Contact     = "[email protected]"
  }
}

# time_static freezes the moment of creation in the state.
# With timestamp() directly, the tag would change on every plan (see 06-02).
resource "time_static" "creation" {}

resource "random_pet" "suffix" {
  length = 2
}

The time_static detail is what separates an ephemeral environment that works from one that produces a dirty plan on every run. We will look at it in depth in 06-02, in the date and time section.

The guard that prevents disaster

# infra/ephemeral/guards.tf

check "only_ephemeral_environments" {
  assert {
    condition     = local.is_ephemeral
    error_message = format(
      "This directory ONLY accepts workspaces with the 'pr-' prefix. Current workspace: '%s'. Permanent environments live in infra/app/.",
      terraform.workspace,
    )
  }
}

data "aws_caller_identity" "current" {}

check "test_account" {
  assert {
    condition     = data.aws_caller_identity.current.account_id == "123456789012"
    error_message = format(
      "Ephemeral environments are only created in the development account 123456789012. You are in %s. Check AWS_PROFILE before continuing.",
      data.aws_caller_identity.current.account_id,
    )
  }
}

Two guards and two risks covered: somebody bringing up an ephemeral environment in the production account, and somebody running this directory with the default workspace and creating resources with no expiry marker that nobody will ever destroy. check blocks are covered in 06-05; here it is enough to know that they warn on every plan without blocking. If you wanted them to block, the same condition as a precondition on a central resource turns it into a hard error, and for this particular guard that is defensible.

Minimal sizing

module "platform" {
  source  = "ecomarket/ecomarket-platform/aws"
  version = "~> 2.0"

  base_name = local.prefix
  suffix    = random_pet.suffix.id

  # An ephemeral environment is the smallest thing that is still representative.
  cidr             = "10.90.0.0/16"
  zones            = slice(data.aws_availability_zones.available.names, 0, 2)
  create_nat       = false            # ~$33/month not being paid
  web_instances    = { min = 1, max = 2, desired = 1 }
  web_class        = "t3.micro"
  db_class         = "db.t3.micro"
  multi_az         = false
  retention_days   = 0                # nobody is going to restore a PR environment
  protect_deletion = false            # it has to be destroyable without friction
  db_password      = var.db_password

  tags = local.common_tags
}

output "environment_url" {
  description = "URL of the ephemeral environment, to post as a comment on the pull request."
  value       = "https://${module.platform.load_balancer_dns}"
}

protect_deletion = false and retention_days = 0 are not oversights: in an ephemeral environment, deletion protection is the failure, because it stops the sweeper doing its job and leaves infrastructure billing away.

The full cycle

flowchart TD
    A["Pull request #482 is opened"] --> B["terraform init"]
    B --> C["terraform workspace select -or-create pr-482"]
    C --> D["terraform apply -var pr_number=482"]
    D --> E["Automatic comment on the pull request<br/>with the environment URL"]
    E --> F["End-to-end tests<br/>against that URL"]
    F --> G{"Closed or<br/>merged?"}
    G -->|"Yes"| H["terraform destroy"]
    H --> I["workspace select default"]
    I --> J["workspace delete pr-482"]
    G -->|"Still open"| K{"Past the 48 h<br/>TTL?"}
    K -->|"Yes"| H
    K -->|"No"| F
#!/usr/bin/env bash
# ci/ephemeral-environment.sh — invoked by the pipeline
set -euo pipefail

: "${PR_NUMBER:?PR_NUMBER is missing}"
: "${ACTION:?ACTION is missing (create|destroy)}"

WS="pr-${PR_NUMBER}"
cd infra/ephemeral

terraform init -input=false

case "$ACTION" in
  create)
    terraform workspace select -or-create=true "$WS"
    terraform apply -input=false -auto-approve \
      -var="pr_number=${PR_NUMBER}" \
      -var="db_password=${TF_VAR_db_password}"
    URL=$(terraform output -raw environment_url)
    echo "environment_url=${URL}" >> "$GITHUB_OUTPUT"
    ;;

  destroy)
    # If the workspace does not exist, there is nothing to do: exit cleanly.
    if ! terraform workspace select "$WS" 2>/dev/null; then
      echo "Workspace ${WS} does not exist. Nothing to destroy."
      exit 0
    fi
    terraform destroy -input=false -auto-approve \
      -var="pr_number=${PR_NUMBER}" \
      -var="db_password=${TF_VAR_db_password}"
    terraform workspace select default
    terraform workspace delete "$WS"
    ;;
esac

Three decisions in the script worth pointing out:

  1. -or-create=true removes the distinction between the first run and later ones. Without it you would need a select with error trapping and a fallback new.
  2. Exiting cleanly if the workspace does not exist stops the destroy job failing when it runs twice, which is common when a pull request is closed and reopened.
  3. The delete comes after select default, because you cannot delete the active workspace.

The sweeper

An ephemeral environment whose pull request has been open for three weeks has stopped being ephemeral. EcoMarket runs a daily scheduled job that corrects this:

#!/usr/bin/env bash
# ci/sweeper.sh — run daily by the scheduled pipeline
set -euo pipefail
cd infra/ephemeral
terraform init -input=false

NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)

for WS in $(terraform workspace list | tr -d '* ' | grep '^pr-'); do
  terraform workspace select "$WS"
  EXPIRES=$(terraform output -raw expires_at 2>/dev/null || echo "")

  if [[ -n "$EXPIRES" && "$EXPIRES" < "$NOW" ]]; then
    echo "::warning::Environment ${WS} expired on ${EXPIRES}. Destroying."
    terraform destroy -auto-approve -var="pr_number=${WS#pr-}"
    terraform workspace select default
    terraform workspace delete "$WS"
  fi
done

Cost warning. An ephemeral EcoMarket environment with the minimal configuration costs between $1 and $3 a day without a NAT gateway (the load balancer and the database are the bulk of it). Twenty pull requests open at once is between $20 and $60 a day, which by the end of the month is between $600 and $1,800. The sweeper is not optional, and neither is a budget alert on the development account. This is the most common way of discovering that ephemeral environments were the most expensive line on the bill.

  1. CLI workspaces versus HCP Terraform workspaces

There is a name collision that causes constant confusion in documentation, forums and interviews. They are called the same and they are different things.

Aspect CLI workspace HCP Terraform / Enterprise workspace
What it is An additional state for the same directory A complete unit of work
Configuration Shared with the other workspaces Its own: its repository and its directory
Variables Shared; only terraform.workspace changes Its own, defined on the platform, with reusable sets
Credentials The same for everybody Its own, per workspace
Permissions Do not exist Per team: read, plan, apply, administer
History None Every run is recorded with who, when and what
Approvals None Configurable manual approval before the apply
Execution On your machine or in your pipeline Remote, on the platform
Cost Free Per managed resource, with a free tier
What it is for Replicas of the same code Actually separating environments

The important takeaway: an HCP Terraform workspace does solve all six problems from section 5, because it is not just another state but a unit with its own configuration, variables, credentials and permissions. When HashiCorp's documentation recommends "one workspace per environment", it means the platform's workspaces, not the CLI's.

And there is one interaction to keep in mind: with the remote or cloud backend, CLI workspaces are projected onto the platform's. With prefix, the CLI workspace prod corresponds to the remote workspace ecomarket-app-prod:

terraform {
  cloud {
    organization = "ecomarket"

    workspaces {
      # The CLI workspace "prod" points at the remote workspace "ecomarket-app-prod"
      tags = ["ecomarket", "app"]
    }
  }
}

The platform itself — remote execution, variable sets, policies, the approval flow — is the subject of 08-04.

  1. Safeguards: consistency guards and the shell prompt

If you use workspaces, and also if you do not use them but want to stop somebody using them by accident, there are two safeguards that cost ten minutes.

The consistency guard

The concrete risk: the active workspace is prod and somebody runs with -var-file=dev.tfvars. The configuration and the data do not match, and the result is rewriting production with development's sizing.

# infra/app/guards.tf

check "workspace_consistent" {
  assert {
    condition = terraform.workspace == "default" || terraform.workspace == var.environment
    error_message = format(
      "Inconsistency: the active workspace is '%s' but the variables loaded are for '%s'. Run 'terraform workspace select %s' or change the -var-file.",
      terraform.workspace,
      var.environment,
      var.environment,
    )
  }
}

The condition allows default because EcoMarket does not use workspaces in this directory: the environment comes from var.environment. What the guard prevents is the mixed state, which is the dangerous one: somebody who half-created a workspace and left the directory in limbo.

If you prefer it to block rather than warn, use the same condition as a precondition on a resource that always exists:

resource "random_pet" "suffix" {
  length = 2

  lifecycle {
    precondition {
      condition = terraform.workspace == "default" || terraform.workspace == var.environment
      error_message = "The active workspace does not match the variables loaded. Check 'terraform workspace show'."
    }
  }
}

The difference between check and precondition — warning versus blocking — is the axis of 06-05.

The shell prompt

No guard replaces seeing the workspace before you type the command. Add this to your shell configuration:

# ~/.bashrc — show the Terraform workspace in the prompt
tf_ws() {
  local ws
  if [[ -f .terraform/environment ]]; then
    ws=$(<.terraform/environment)
  elif [[ -d .terraform ]]; then
    ws="default"
  else
    return
  fi

  # Red for production, yellow for everything else.
  if [[ "$ws" == *prod* ]]; then
    printf ' \033[41;97m TF:%s \033[0m' "$ws"
  else
    printf ' \033[43;30m tf:%s \033[0m' "$ws"
  fi
}

PS1='\w$(tf_ws) \$ '

The red background for production is not decoration. Ergonomics is part of risk control: a dangerous environment must look different. Anyone using starship, oh-my-zsh or powerlevel10k has ready-made Terraform modules that do the same thing, and the same goes for the active AWS profile, which deserves identical treatment.

Common Mistakes and Tips

Believing a workspace separates credentials or backends. It does not. It is an additional state in the same backend, reachable with the same credentials. If your reason for using workspaces was to isolate production, the mechanism does not do what you expect.

Leaving the environment name inside key when adopting workspaces. The result is env:/prod/ecomarket/dev/app/terraform.tfstate: the production state at a path that says dev. If you use workspaces, the key must be neutral.

Running terraform workspace delete believing it destroys the infrastructure. It deletes the state. The infrastructure is still alive, with nobody managing it and the bill running. First destroy, then delete. And -force is the direct route to orphaned infrastructure.

Forgetting yesterday's selected workspace. It is accident number one. The workspace persists in .terraform/environment, does not appear in the repository and is not visible in the plan. Shell prompt and terraform workspace show before every apply.

Indexing the sizing map with no default value. local.sizing[terraform.workspace] blows up with Invalid index as soon as somebody creates a new workspace. Use lookup(map, terraform.workspace, map["default"]).

Putting terraform.workspace inside a reusable module. It couples the module to the workspace name of whoever consumes it. A module receives its parameters; it does not query the environment.

Leaving TF_WORKSPACE exported in your shell. It overrides select and affects every command in the session, including the destroy. Use it inline only, in front of the specific command.

Using workspaces for environments because "it is what Terraform ships". The mechanism existing does not mean it solves your problem. HashiCorp's own documentation advises against CLI workspaces as an environment separator and recommends separate directories.

Not giving ephemeral environments a sweeper. Twenty open pull requests are twenty platforms on the meter. The TTL in tags and a daily scheduled job are part of the design, not an extra.

Creating workspaces with names that are neither URL-safe nor consistent. PR 482, pr/482 and pr-482 all end up in resource names. Fix a convention and validate it with startswith or a regular expression.

Tip: if in doubt, do not use workspaces. The cost of starting with directories and .tfvars and discovering that workspaces would have been enough is low. The cost of starting with workspaces and discovering nine months in that production needs to diverge is a state migration with the platform running.

Exercises

Exercise 1: diagnosing the S3 keys

A team has adopted workspaces on top of this configuration, which dates from the days of a single environment:

terraform {
  backend "s3" {
    bucket         = "ecomarket-tfstate-123456789012"
    key            = "ecomarket/dev/platform/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "ecomarket-tfstate-locks"
  }
}

They have created the staging and prod workspaces and applied in all three.

  1. Write out the three exact keys that now exist in the bucket.
  2. Explain the concrete problem with the IAM policy that was meant to give a team read-only access to the production state using the pattern arn:aws:s3:::ecomarket-tfstate-123456789012/ecomarket/prod/*.
  3. Propose the corrected configuration and describe the steps for migrating without losing state.

Exercise 2: choosing the strategy

For each of these four scenarios, choose between CLI workspaces, a directory per environment, separate repositories or Terragrunt. Justify your answer with at least two criteria from the table in section 7.

  • A. EcoMarket deploys its shop in four regions with an identical configuration except for region, CIDR and domain. All in the same production account, applied by the same team.
  • B. EcoMarket has dev, staging and prod in three different accounts. Production has a WAF, a read replica and cross-region bucket replication; development has none of that. The application team can apply in dev, but only the platform team can apply in prod.
  • C. EcoMarket needs a complete environment for every pull request, living less than two days.
  • D. EcoMarket grows to twelve environments (three permanent ones in each of four regions). The backend.tf files, the provider blocks and the module calls are almost identical and have already drifted out of sync twice.

Exercise 3: the missing guard

Write the configuration for infra/ephemeral/ that prevents the following three accidents, stating in each case whether it should block or merely warn, and why:

  1. Applying the ephemeral-environments directory with the default workspace.
  2. Creating an ephemeral environment in an account other than development (123456789012).
  3. Creating an ephemeral environment with production sizing (an instance class not on the allowed list).

Also add an expires_at output that the sweeper from section 9 can read with terraform output -raw.


Solutions

Solution 1

1. The three keys:

ecomarket/dev/platform/terraform.tfstate                 ← workspace "default"
env:/staging/ecomarket/dev/platform/terraform.tfstate    ← workspace "staging"
env:/prod/ecomarket/dev/platform/terraform.tfstate       ← workspace "prod"

The dev segment appears in all three, production included, because the workspace prefix is prepended to the complete key instead of replacing any part of it.

2. The problem with the policy:

{
  "Effect": "Allow",
  "Action": ["s3:GetObject"],
  "Resource": "arn:aws:s3:::ecomarket-tfstate-123456789012/ecomarket/prod/*"
}

That policy grants nothing: no object in the bucket starts with ecomarket/prod/. The production state is at env:/prod/ecomarket/dev/platform/terraform.tfstate. The correct pattern would be env:/prod/*, with two drawbacks: it contains a : character that forces you to check escaping, and the resulting structure mixes the workspace name with a path that says dev, which makes the policy unreadable for anyone auditing it.

Worse still: anybody wanting to grant access to the development state with ecomarket/dev/* would be granting access to default's and, if the pattern is written with a leading wildcard, potentially to all three.

3. Corrected configuration and migration:

terraform {
  backend "s3" {
    bucket               = "ecomarket-tfstate-123456789012"
    key                  = "platform/terraform.tfstate"     # neutral
    workspace_key_prefix = "environments"                   # no ':'
    region               = "eu-west-1"
    use_lockfile         = true
  }
}

Resulting keys: platform/terraform.tfstate (default), environments/staging/platform/terraform.tfstate, environments/prod/platform/terraform.tfstate. Now environments/prod/* is a readable policy pattern.

Migration steps, workspace by workspace and with a backup first:

# 1. Back up the three states BEFORE touching anything
for WS in default staging prod; do
  terraform workspace select "$WS"
  terraform state pull > "backup-${WS}-$(date +%F).tfstate"
done

# 2. Change backend.tf to the corrected configuration

# 3. Reinitialise with state migration, workspace by workspace
terraform init -migrate-state

# 4. Verify: a zero-change plan in each workspace
for WS in default staging prod; do
  terraform workspace select "$WS"
  terraform plan -detailed-exitcode || echo "WARNING: $WS is not clean"
done

Step 4 is non-negotiable: a plan that does not come out empty means the migrated state does not correspond to the infrastructure, and you have to stop there. If something goes wrong, the files from step 1 let you go back with terraform state push.

Solution 2

A. Four identical regions → CLI workspaces.

  • Configuration divergence: none is wanted. Having the mechanism prevent it is an advantage: the four regions must be the same platform.
  • Credential isolation: irrelevant, it is the same account and the same team. Objection 5.2 does not apply.
  • Duplication: none, as against four nearly identical directories that would have to be kept in sync by hand.
  • The local.regions map indexed by terraform.workspace is exactly case B from section 8.
  • Watch out: the day one region needs a resource of its own, revisit the decision.

B. Three environments with different accounts and permissions → a directory per environment.

  • Different permissions per environment: workspaces do not support them at all, and the brief requires them. With directories, path-based owner rules and a protected environment in the pipeline for infra/prod/ solve it without inventing anything.
  • Configuration divergence: WAF, replica and cross-region replication are structural differences, not size differences. With workspaces they would be three or more conditionals on terraform.workspace in the very code that dev also reads.
  • Provider versions per environment: with a single lock, upgrading the provider in dev upgrades it in prod. Unacceptable with real production.
  • Risk of human error: three different accounts require three provider configurations; directories make that explicit.

C. One environment per pull request → CLI workspaces.

  • Ephemeral environments: this is the row where workspaces win without argument. Creating and deleting directories on the fly is unworkable in a pipeline.
  • Divergence: an environment that lives 48 hours has no time to diverge. Objection 5.4 never materialises.
  • Maintenance cost: minimal, two commands in the pipeline.
  • With the three conditions from section 9: a pr- prefix guard, an account guard and a sweeper with a TTL.

D. Twelve environments with duplicated scaffolding, already out of sync → Terragrunt.

  • Code duplication: twelve almost identical backend.tf files is precisely the problem Terragrunt solves by generating the backend configuration by convention.
  • Maintenance cost: the drift has already happened twice; it is a measured symptom, not a hypothesis.
  • Isolation and permissions: they are preserved, because each environment still has its directory and its role.
  • Trade-off: a dependency on an external tool and a learning curve. It is the subject of 07-05.

Solution 3

# infra/ephemeral/guards.tf

locals {
  is_ephemeral = startswith(terraform.workspace, "pr-")

  # List of classes allowed in ephemeral environments: free tier only.
  allowed_classes = ["t3.micro", "t3.small", "t4g.micro", "t4g.small"]
}

# 1. BLOCKS. Applying with the "default" workspace would create resources
#    with no expiry marker that the sweeper will never destroy: that is a
#    permanent, invisible cost. It must stop the apply, not merely warn.
resource "time_static" "creation" {
  lifecycle {
    precondition {
      condition = local.is_ephemeral
      error_message = format(
        "Workspace '%s' is not valid. This directory only accepts 'pr-<number>' workspaces. Run: terraform workspace select -or-create pr-<number>",
        terraform.workspace,
      )
    }
  }
}

# 2. BLOCKS. Creating an ephemeral environment in the production account is
#    the most expensive accident possible: resources with test names and no
#    protection living alongside production. It must not reach the apply.
data "aws_caller_identity" "current" {}

resource "random_pet" "suffix" {
  length = 2

  lifecycle {
    precondition {
      condition     = data.aws_caller_identity.current.account_id == "123456789012"
      error_message = format(
        "Ephemeral environments are only created in the development account 123456789012. Active credentials: account %s. Check AWS_PROFILE.",
        data.aws_caller_identity.current.account_id,
      )
    }
  }
}

# 3. WARNS. Excessive sizing is expensive, but it is neither destructive nor
#    irreversible: the sweeper will destroy it in 48 hours anyway. A check
#    leaves a record in the plan and in the pipeline log without getting in
#    the way of somebody with a legitimate reason to ask for a bigger machine.
check "contained_sizing" {
  assert {
    condition     = contains(local.allowed_classes, var.web_class)
    error_message = format(
      "Class '%s' is not on the list of classes allowed for ephemeral environments (%s). A pull request environment should not cost more than the pull request.",
      var.web_class,
      join(", ", local.allowed_classes),
    )
  }
}

And the output the sweeper consumes:

# infra/ephemeral/outputs.tf

variable "ttl_hours" {
  type    = number
  default = 48
}

output "expires_at" {
  description = "RFC3339 instant from which the sweeper may destroy this environment."
  value       = timeadd(time_static.creation.rfc3339, "${var.ttl_hours}h")
}

Why time_static and not timestamp(). timestamp() is evaluated on every plan, so expires_at would change on every run, the environment would never expire and, on top of that, the plan would never be clean. time_static.creation freezes the instant in the state: it is fixed when the resource is born and never moves again. The same reasoning applies to the ExpiresAt tag from section 9, and you will see it in more detail in 06-02.

Why two blocks and one warning. The criterion is irreversible damage. The wrong workspace and the wrong account produce resources nobody will clean up or that live alongside production: those are mistakes the apply must never get to make. Excessive sizing produces a slightly larger bill for 48 hours: that is a mistake worth flagging, not preventing. That distinction — what breaks the plan and what merely warns — is the axis of 06-05.

Conclusion

Workspaces were the oldest debt in the course and it is now settled, with the nuance that matters: they are not bad, they are specific.

  • A CLI workspace is an additional state for the same configuration and the same backend. No more, no less. It does not separate code, credentials, backends or permissions.
  • In S3, a workspace's state goes to <workspace_key_prefix>/<ws>/<key>, with env: by default. If the key already had the environment inside it, the result is a contradictory path such as env:/prod/ecomarket/dev/..., and IAM policies written against the old path stop granting anything.
  • Five commands: list, show, new (creates and selects, accepts -state for seeding), select (with -or-create since 1.4) and delete, which deletes the state and destroys nothing. The safe order is always destroy → select default → delete.
  • terraform.workspace enables four patterns — name suffix, sizing map, environment conditional and conditional resource — in decreasing order of advisability. The map with lookup and a default value is the only one that ages well.
  • The six problems they do not solve: one configuration for everybody, the same credentials and the same backend, the risk of applying in the wrong workspace, divergence that grows over time, the impossibility of granting different permissions, and the shared provider lock. The last two, on their own, rule workspaces out for separating environments with real production.
  • EcoMarket chose an explicit var.environment, per-environment .tfvars, a backend with a per-environment key and separate accounts because the environment must be a visible piece of data in the command, reviewable in the pull request and set by the pipeline, not an invisible piece of state on the laptop of whoever runs it.
  • They really are the right tool for ephemeral environments per pull request, identical replicas per region or per customer, and personal labs. The criterion is one question: are they the same code today and a year from now?
  • The complete ephemeral environment needs four pieces: the workspace as the identifier, time_static for a stable expiry marker, guards that prevent the wrong workspace and the wrong account, and a scheduled sweeper. Without the fourth, ephemeral environments are the most expensive line on the bill.
  • HCP Terraform workspaces are called the same and are something else: units with their own configuration, variables, credentials, permissions and history. Those do separate environments, and they are the subject of 08-04.
  • Two cheap safeguards: a guard comparing terraform.workspace with var.environment, and a shell prompt that shows the active workspace on a red background when it is production.

The next lesson, Terraform Functions, settles the second debt from module 5: the functions you have been using without taking them apart. cidrsubnet, which computes EcoMarket's subnets and whose 100-position offset we still have not justified bit by bit; templatefile, which injects the PostgreSQL endpoint into the user_data; merge, which composes local.common_tags and which you have just seen again in the auto scaling group's dynamic "tag"; and try, which holds up the optional references. You will see the full catalogue organised by what you need to do, you will learn to test everything in terraform console before writing it into a .tf, and you will find the traps that turn an innocent function into a plan that never converges.

© Copyright 2026. All rights reserved