Skip to content
Hands-on IT IT Drills

Day 10: Environments – dev and prod

Goal: Run the same infrastructure several times – once with workspaces, once with one directory per environment – and see the pros and cons in your own lab. · Duration: approx. 75 min · Prerequisite: Day 9

Briefing

  • An environment (dev, test, prod) is the same configuration with different values and, above all, with its own state. If two environments share a state, one overwrites the other (Day 2, Challenge).
  • Workspaces give one directory several states. terraform.workspace contains the name of the active one. Quick to set up – but you can’t tell from the command line which one is currently active.
  • One directory per environment (envs/dev, envs/prod) with its own backend key and its own values. More files, but every difference is visible in the code.
 Workspaces:   tag10/ws ─ workspace dev  ─► S3: env:/dev/tag10/ws.tfstate
                        └ workspace prod ─► S3: env:/prod/tag10/ws.tfstate
 Directories:   tag10/envs/dev  ─► S3: tag10/dev.tfstate   (dev.auto.tfvars)
                tag10/envs/prod ─► S3: tag10/prod.tfstate  (prod.auto.tfvars)

Drill 1: Workspaces

mkdir -p ~/tf-lab/tag10/ws && cd ~/tf-lab/tag10/ws
sed 's|tag05/terraform.tfstate|tag10/ws.tfstate|' ~/tf-lab/tag05/backend.tf > backend.tf
cp ~/tf-lab/tag05/versions.tf .
cat > main.tf <<'EOF'
provider "docker" {}

locals {
  ports = { dev = 8091, prod = 8092 }
}

module "notes" {
  source      = "git::file:///home/ubuntu/tf-lab/module//notes-docker?ref=v1.1.0"
  name        = "ws-${terraform.workspace}"
  port        = local.ports[terraform.workspace]
  db_passwort = "lab-db-pw-123"
}

output "url" {
  value = module.notes.url
}
EOF
tofu init -no-color >/dev/null
tofu workspace new dev -no-color | head -1
tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu workspace new prod -no-color | head -1
tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu workspace list
tofu output -raw url; echo
s3ls 'tofu-state?list-type=2' | grep -o '<Key>[^<]*tag10[^<]*</Key>'

Expected:

Created and switched to workspace "dev"!
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
Created and switched to workspace "prod"!
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
  default
  dev
* prod
http://127.0.0.1:8092
<Key>env:/dev/tag10/ws.tfstate</Key>
<Key>env:/prod/tag10/ws.tfstate</Key>
  • One directory, three states: default (empty), dev, prod. In the bucket, the workspaces live under env:/<name>/.
  • local.ports[terraform.workspace] picks the port by name. The plan rejects a workspace that isn’t in the map.
  • For brevity without encryption.tf – in a real project it belongs here too.

Save your progress? Sign up for free

Drill 2: The Trap

A new database password, for dev only at first – but which workspace is active?

sed -i 's/lab-db-pw-123/lab-db-pw-456/' main.tf
tofu plan -no-color | grep -E 'must be replaced|Plan:'
tofu workspace show

Expected:

  # module.notes.docker_container.api["a"] must be replaced
  # module.notes.docker_container.db must be replaced
  # module.notes.docker_container.migrate must be replaced
Plan: 3 to add, 0 to change, 3 to destroy.
prod

dev was intended, prod is being planned – database and containers would be replaced. With workspaces, an invisible setting in the .terraform directory decides which environment you hit. That’s why many teams show the workspace in their prompt – or avoid workspaces entirely for real environments.

sed -i 's/lab-db-pw-456/lab-db-pw-123/' main.tf
tofu workspace select dev -no-color
tofu plan -no-color | tail -1

Expected:

Switched to workspace "dev".
No changes. Your infrastructure matches the configuration.

Save your progress? Sign up for free

Drill 3: One Directory per Environment

mkdir -p ~/tf-lab/tag10/envs/{dev,prod} && cd ~/tf-lab/tag10/envs
for u in dev prod; do
  sed "s|tag05/terraform.tfstate|tag10/$u.tfstate|" ~/tf-lab/tag05/backend.tf \
    > $u/backend.tf
  cp ~/tf-lab/tag05/versions.tf $u/
  cat > $u/main.tf <<'EOF'
provider "docker" {}

variable "umgebung" { type = string }
variable "port" { type = number }
variable "instanzen" { type = set(string) }

module "notes" {
  source      = "git::file:///home/ubuntu/tf-lab/module//notes-docker?ref=v1.1.0"
  name        = "env-${var.umgebung}"
  port        = var.port
  instanzen   = var.instanzen
  db_passwort = "lab-db-pw-123"
}
EOF
done
printf 'umgebung  = "dev"\nport      = 8093\ninstanzen = ["a"]\n' > dev/dev.auto.tfvars
printf 'umgebung  = "prod"\nport      = 8094\ninstanzen = ["a", "b"]\n' \
  > prod/prod.auto.tfvars
diff dev/main.tf prod/main.tf && echo "gleicher Code"
diff dev/dev.auto.tfvars prod/prod.auto.tfvars
for u in dev prod; do
  tofu -chdir=$u init -no-color >/dev/null
  tofu -chdir=$u apply -auto-approve -no-color | grep 'Apply complete'
done

Expected:

gleicher Code
1,3c1,3
< umgebung  = "dev"
< port      = 8093
< instanzen = ["a"]
---
> umgebung  = "prod"
> port      = 8094
> instanzen = ["a", "b"]
Apply complete! Resources: 9 added, 0 changed, 0 destroyed.
Apply complete! Resources: 10 added, 0 changed, 0 destroyed.
  • tofu -chdir=dev works in the subdirectory – where you’re currently standing doesn’t matter. Which environment is meant is right there on the command line.
  • The difference between the environments is exactly one file. A review sees immediately what prod does differently.
  • main.tf is identical in both folders. Larger projects store it once and include it as a module – or use tools like Terragrunt.

Save your progress? Sign up for free

Drill 4: A Change for dev Only

sed -i 's/^instanzen = \["a"\]$/instanzen = ["a", "c"]/' dev/dev.auto.tfvars
tofu -chdir=dev plan -no-color | grep -E 'will be created|Plan:'
tofu -chdir=prod plan -no-color | tail -1
tofu -chdir=dev apply -auto-approve -no-color | grep 'Apply complete'

Expected:

  # module.notes.docker_container.api["c"] will be created
Plan: 2 to add, 0 to change, 1 to destroy.
No changes. Your infrastructure matches the configuration.
Apply complete! Resources: 2 added, 0 changed, 1 destroyed.

A new instance plus a new proxy (the nginx configuration changes) – in dev, and only there. prod stays untouched because it has its own state and its own values.

Save your progress? Sign up for free

Checkpoint

for p in 8091 8093 8094; do curl -s -o /dev/null -w "$p %{http_code}\n" \
  http://127.0.0.1:$p/healthz; done

Expected: dev in the workspace, dev and prod in the directories.

8091 200
8093 200
8094 200
s3ls 'tofu-state?list-type=2' | grep -o '<Key>[^<]*tag10[^<]*' | wc -l

Expected:

4
cd ~/tf-lab/tag10/ws && tofu workspace show

Expected:

dev

Challenge

The workspace variant should keep only one environment: tear down prod in the workspace completely and delete the workspace. The container on port 8092 must be gone afterwards; dev on 8091 keeps running.

Hint: You can only delete a workspace if its state is empty and it isn’t active.

Solution

cd ~/tf-lab/tag10/ws
tofu workspace select prod -no-color
tofu destroy -auto-approve -no-color | grep 'Destroy complete'
tofu workspace select dev -no-color
tofu workspace delete prod -no-color
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8092/healthz
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8091/healthz

Expected:

Switched to workspace "prod".
Destroy complete! Resources: 9 destroyed.
Switched to workspace "dev".
Deleted workspace "prod"!
000
200

Save your progress? Sign up for free

Enterprise Note

  • Directories for environments, workspaces for copies: Workspaces suit many identical, short-lived copies (one per feature branch). For dev/test/prod with their own permissions and approvals, directories are clearer.
  • Separate credentials per environment: prod gets its own backend path with its own permissions and its own provider credentials. Someone who may only change dev then can’t hit prod at all.
  • Same code, same version: Differences between environments belong in values, not in diverging copies of the code. A module with a pinned version for everyone makes that safe.