Managing dev, staging and prod in Terraform: workspaces vs directories
The same shorty network built for dev, staging and prod twice: once with Terraform workspaces and once with a folder per environment. Where each state file ends up in S3, the guard I added for the default workspace, and why I pick directories.
Sooner or later every Terraform project needs a second copy of itself. A dev environment to break things in, maybe a staging, and prod. The code should be the same, the sizes and the state should not.
There are two common ways to do this with plain Terraform: workspaces, where one folder has several states, and directories, where each environment has its own folder. In this blog we will build the same thing both ways, look at where the state ends up, and I'll say which one I'd pick and why. Level: intermediate. It uses the VPC module from the module post and the S3 backend from the state post. I used Terraform 1.17.1 and AWS provider 6.73.0.
What has to be different
For the shorty network, the three environments differ in a few values.
| dev | staging | prod | |
|---|---|---|---|
| CIDR | 10.10.0.0/16 | 10.20.0.0/16 | 10.30.0.0/16 |
| Zones | 1 | 2 | 3 |
| NAT gateway | no | no | yes |
Everything else is the module. What really matters though is the state. Each environment needs its own state, so a plan in dev can never show a change to prod, and a broken apply in dev can't corrupt prod's state. Both approaches give you separate states. They differ in how easy it is to point at the wrong one.
If you want to see what the module actually builds, the VPC by hand post does the same thing in the console, step by step.
Option 1: workspaces
One folder, one backend block, and the environment comes from terraform.workspace.
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
backend "s3" {
bucket = "tfstate-111122223333-ap-south-1"
key = "shorty/network.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
provider "aws" {
region = "ap-south-1"
}
locals {
settings = {
dev = {
cidr_block = "10.10.0.0/16"
azs = ["ap-south-1a"]
nat = false
}
staging = {
cidr_block = "10.20.0.0/16"
azs = ["ap-south-1a", "ap-south-1b"]
nat = false
}
prod = {
cidr_block = "10.30.0.0/16"
azs = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
nat = true
}
}
# Falls back to dev values so "terraform validate" works in the
# default workspace. The guard below stops a real plan there.
env = lookup(local.settings, terraform.workspace, local.settings["dev"])
}
resource "terraform_data" "workspace_guard" {
lifecycle {
precondition {
condition = contains(keys(local.settings), terraform.workspace)
error_message = "Select a workspace first: terraform workspace select dev (or staging, prod)."
}
}
}
module "vpc" {
source = "../modules/vpc"
name = "shorty-${terraform.workspace}"
cidr_block = local.env.cidr_block
azs = local.env.azs
enable_nat_gateway = local.env.nat
tags = {
Project = "shorty"
Environment = terraform.workspace
}
}
output "vpc_id" {
value = module.vpc.vpc_id
}
That guard has a story. My first version was simpler, env = local.settings[terraform.workspace], so the default workspace would just fail. It did fail. It also failed terraform validate, because validate runs in the default workspace too.
Error: Invalid index
on main.tf line 45, in locals:
45: env = local.settings[terraform.workspace]
├────────────────
│ local.settings is object with 3 attributes
│ terraform.workspace is "default"
The given key does not identify an element in this collection value.
A config that can't pass validate is no good in CI. So now the lookup falls back to dev values and a terraform_data resource with a precondition stops any plan in an unknown workspace.
The workspace commands:
terraform init
terraform workspace new dev
terraform workspace new prod
terraform workspace list
default
dev
* prod
The star is the one you're in. workspace new also switches to it, so after those commands I was in prod without typing select. Keep that in mind.
I ran all of this against moto, a local AWS mock, with a fake bucket and fake credentials, so I could look inside the bucket afterwards. After creating the two workspaces it held these keys:
env:/dev/shorty/network.tfstate
env:/prod/shorty/network.tfstate
So each workspace gets its own state object under env:/<workspace>/, in the same bucket, next to the same key. The default workspace would use the plain key.
Then the plans. In dev it planned 9 resources (8 for the VPC plus the guard), in prod 19. And in default:
Terraform planned the following actions, but then encountered a problem:
# module.vpc.aws_internet_gateway.this will be created
...
Plan: 8 to add, 0 to change, 0 to destroy.
Error: Resource precondition failed
on main.tf line 51, in resource "terraform_data" "workspace_guard":
51: condition = contains(keys(local.settings), terraform.workspace)
├────────────────
│ local.settings is object with 3 attributes
│ terraform.workspace is "default"
Select a workspace first: terraform workspace select dev (or staging, prod).
It still printed the dev-sized plan above the error, which gave me a small jump the first time. But a plan with errors can't be applied, so it's safe.
Option 2: a folder per environment
Same module, three small root modules.
modules/
vpc/
envs/
dev/
backend.tf
main.tf
staging/
backend.tf
main.tf
prod/
backend.tf
main.tf
envs/prod/backend.tf:
terraform {
backend "s3" {
bucket = "tfstate-111122223333-ap-south-1"
key = "shorty/prod/network.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
envs/prod/main.tf, with the values written out:
terraform {
required_version = ">= 1.11"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
module "vpc" {
source = "../../modules/vpc"
name = "shorty-prod"
cidr_block = "10.30.0.0/16"
azs = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
enable_nat_gateway = true
tags = {
Project = "shorty"
Environment = "prod"
}
}
output "vpc_id" {
value = module.vpc.vpc_id
}
Dev and staging are the same two files with their own values. Against the mock, envs/dev planned 8 resources and envs/prod planned 18. To work on prod you cd envs/prod, and your shell prompt tells you where you are.
Yes, there's some repetition. The provider block and the terraform block are copied three times. I'm actually fine with that. It's boring code that rarely changes, and the module holds the real logic.
Comparing them
Workspaces are less code. One folder, one set of files, and adding an environment is one command. But see, the environment you're in is invisible. It's stored in .terraform/environment, not in the path or the files, and terraform plan looks exactly the same in dev and in prod. All environments also share one backend config and whatever credentials you have in the shell at that moment. You can't easily say "prod state lives in the prod account" when the backend block is shared.
Directories cost a bit more typing and in return everything is visible. The path says which environment it is. Each folder can have a different backend, a different AWS account, a different provider version if you're upgrading prod last. Each can have its own CI job with its own credentials and an approval step only on prod. A code review shows exactly which environment a change touches, because the diff is in envs/prod/. The CI/CD basics post talks about promoting the same change through environments, and folders make that easy to see.
So for long-lived environments like dev, staging and prod, I pick directories. Workspaces I'd use for short-lived copies of the same environment, for example a throwaway stack per feature branch, where all copies really are identical and get deleted in a week.
One more thing about my own setup, to be honest about it: the Terraform for this blog has exactly one environment, and it's prod. There is no staging fenixara.com. For a single small server that's a choice I'm OK with, but the day it gets a staging copy, it'll be a second folder.
Where Terragrunt fits
If you end up with ten environments times five components, the copied backend.tf and provider blocks does start to add up. That's the problem Terragrunt solves. It's a thin wrapper around Terraform that generates the backend and provider config from one place and passes inputs to each folder. You keep the directory layout, and the repetition goes away. I wouldn't start with it. Three folders are easy to read without any extra tool, and you can add Terragrunt later without changing the module.
Also, the word "workspace" means something else in HCP Terraform (the hosted product). There a workspace is closer to a folder with its own state, variables and permissions. This post is about the CLI workspaces only.
That's it. Whatever you choose, run terraform workspace show or pwd before every apply, it takes one second only.