On this page:
Part 1 of 4 of Build and destroy a bunch: one stack per service: The concepts (why one stack per service, layout, passing values, build and destroy order, tags, costs, lessons), then the start of the free path: costs and the Bash setup script.
Next: The PowerShell lab and exercises 1 to 4
Unfamiliar word or acronym? The Glossary defines it.
Status: the free lab was run on Linux; the cloud lab was only validated, never applied; PowerShell was not run. On 2026-10-22 the author ran the whole free lab on Linux with OpenTofu 1.12.6 (the version CI pins) and the
hashicorp/localprovider 2.9.1: five full build-and-destroy cycles, each ending with a checker that found every state empty, plus the wrong-order and forgotten-resource exercises (Exercise 5 and Exercise 6); the output shown is from that run, trimmed. The cloud lab's five stacks were checked withtofu initandtofu validateagainst thedigitalocean/digitaloceanprovider 2.106.0 (a schema check: no token, no API call, nothing created), so their argument names are right, but nothing in them was ever applied. Expect to fix something. The PowerShell scripts were written from Microsoft's and OpenTofu's documentation and were not run (there was no Windows machine): treat every PowerShell line as est. Vendor facts come from the pages listed in the claims register, read on 2026-10-22. Nothing here was run against this project's own stacks, which are locked. Prerequisites. The three earlier lessons of the track: OpenTofu from zero (init, plan, apply, destroy), Plans, state, drift and recovery and Spacelift from zero. If you want less first, What is infrastructure as code and OpenTofu, stacks and modules cover the minimum (provider, resource, plan, apply, state, stack). Also useful: The terminal and your first script and Teardown checklist. The free lab needs OpenTofu 1.8 or newer, a terminal and a few megabytes of disk; no account, no money. About 60 minutes of reading and 90 minutes for the free lab (est.); the optional cloud lab adds about an hour (est.) and uses your own account.
| Idea | Where it is today | The gap this page fills |
|---|---|---|
| Stack, module, layered stacks | OpenTofu, stacks and modules gives five reasons for layers and says outputs flow from 00 to 10 through Spacelift dependencies. | It describes this project's three stacks. It does not teach the general rule, the costs of splitting, or what to do with fifteen stacks. |
| Destroy order and leftovers | Teardown checklist gives the order and the proof commands for this project. | It is a checklist for one environment. The reasons, the hazards and a practice loop are here. |
| Cost per stack | Cost and CI, tests and the cost gate explain the gate. | Nothing teaches a learner to compute a budget for their own run. |
| Running stacks | Spacelift shows the run lifecycle for this project. | It does not show building and destroying a whole set again and again. |
First the words. A stack is a folder of OpenTofu code that you plan and apply as one unit, with its own state (the file or record of what that code created). A service here means anything one person or team can own, change and switch off on its own: the network, a firewall baseline, one web application, a logging server. One stack per service means one folder, one state, one plan, one apply and one destroy for each.
| Reason | What it buys | A small example |
|---|---|---|
| Blast radius (what it means) | A mistake can only touch what is in that stack's state. | A bad edit to the web app's stack cannot plan a change to the network, because the network is not in that state. |
| State isolation | One state file, one lock, one thing to corrupt or lose. State often holds sensitive values, so fewer secrets per file is a smaller loss. | Two people can apply two services at the same time; only two applies to the same stack have to wait for each other. |
| Trust boundary | Each stack runs with its own credentials and identity, so what one stack's credentials can reach is limited to what that stack needs. The maintainer's ruling for this project is that stack boundaries are trust boundaries: for example, the lxmd service and Reticulum get separate stacks and separate identities, so a mistake or a compromise in one does not carry into the other. | The token for the logging stack cannot touch the network. |
| Ownership | A folder can have an owner, a reviewer and a set of permissions. | The team that runs the web app can change the web app, and is not able to change the network by accident. |
| Independent destroy | You can switch one service off, or rebuild it, without touching the others. | Rebuild a test server nightly while the network stays up. |
| Cost gating per stack | Each stack declares its own spend, so a price change shows up in the right place. | This project keeps one cost.json per stack; see the cost gate. |
| Faster, readable plans | A short plan gets read; a 300-line plan gets skimmed. Fewer resources also means a quicker refresh. | The human who confirms an apply can actually read it. |
Splitting is a trade, not a free win. The costs are real, and they are why you should not split everything.
| Cost | What it looks like | What softens it |
|---|---|---|
| Cross-stack wiring | A value one stack creates (a network ID) is needed by another, so you must publish it and read it. | Few, boring outputs (IDs and names), pinned by a test. See Passing values between stacks. |
| Ordering | Stacks must be built in dependency order and destroyed in the reverse. Get it wrong and a run fails, sometimes half way. | A written order, a script, or the platform's dependency feature. See Build order and destroy order. |
| More runs and more approvals | Ten stacks are ten plans to read. A change that touches three of them is three pull requests or three runs. | Keep the number of stacks to what ownership and change rate justify; use a factory (below) to create stacks the same way each time. |
| Duplicated setup | Each stack repeats the provider block, the backend and the variables. | Put the reusable parts in modules; keep the per-stack code to wiring. |
| Harder refactors | Moving a resource from one stack's state to another's is a careful, manual step. | Decide boundaries early; move with tofu state commands or moved and import blocks, never by hand-editing state. |
| Partial failure | With one stack, a run either worked or it did not. With five, you can end up with three built and two not. | Make every stack safe to run again, and keep a "what is built right now" check (the lab below has one). |
Rule of thumb: split along ownership, change rate and blast radius. Things that always change together, and are owned by the same person, can stay in one stack. A single-person throwaway lab in one folder is fine. An environment where the network changes yearly and an application changes daily is not.
The free lab you will build has this shape. Each box is a folder with its own state; an arrow means "reads an output of".
00-tag <---------- 10-firewall <------- 20-network <--+---- 30-server-a
^ ^ ^ |
| | | +---- 40-server-b
+----------------------+--------------------+ (every stack also reads 00-tag)
Build order: 00-tag, 10-firewall, 20-network, 30-server-a, 40-server-b. Destroy order: exactly backwards. In the cloud lab the same five boxes are a tag, a firewall that is attached by that tag, a private network, and two small servers.
stacks/<NN>-<name>/ with its own main.tf, variables.tf, outputs.tf, versions.tf and tests. This project's stacks are 00-foundation, 10-access and 20-telemetry.00, 10, 20 leave room to slot a layer in later without renaming. The number is the build order; the name says what it is.<layer>-<region>-<role>. The lab's names carry a prefix (cah-lab-) so a script can find everything the lab made.terraform.tfvars.example is committed and *.tfvars is ignored, so values with an account in them never reach Git. (The lab's terraform.tfvars files live in your scratch folder and hold no secrets.) See Variables, tfvars and secrets.00-tag is in its needs list.cost.json here), read by the cost gate.tests/*.tftest.hcl files with mocked providers, so CI proves the shape for free.Once the network lives in one stack and the server in another, the server needs the network's ID. There are four ways, and each has a catch.
| Way | How it works | Catch |
|---|---|---|
| Remote state data source | The consumer reads the producer's root module outputs with data "terraform_remote_state". The free lab does this. |
OpenTofu's documentation warns that the reader needs access to the entire state snapshot, which often includes sensitive information, and that the data source does not respect the sensitivity of the source state. |
| Spacelift stack dependency with an output reference | A downstream stack lists an upstream stack's output and maps it to an environment variable, TF_VAR_<name> for OpenTofu. This project does this, so stack 10 never has read access to stack 00's whole state, only the values it consumes. |
It only respects tracked runs, uses the outputs of a successful run that included an apply, and (per Spacelift's documentation) does not manage creating or deleting stacks. See Spacelift and the third lesson of the track. |
| Lookup by tag or name | The consumer uses a provider data source to find the resource that exists, by its tag or name. | The thing must already exist and the name must be stable. There is no recorded link, so destroy order is not enforced by anything. |
| Publish somewhere on purpose | One stack writes the shared value to a named place (a parameter store, a DNS record); others read it there. OpenTofu's documentation recommends this when you can, because it lets you set different access for shared data and for state. | One more moving part to run. |
Never pass a secret this way. An output lands in the state, state sits somewhere (a plain-text JSON file when it is local, per OpenTofu's documentation), and a stack dependency copies it into another stack's environment and logs. Pass identifiers: IDs, names, CIDR ranges, tag names. Pass secrets by giving each stack its own read of the secret store (this project uses Doppler with a per-stack list of the names a stack may load), and mark sensitive outputs sensitive = true knowing that this hides them in the terminal, not in the state file.
A quick test for a candidate output: "if this value appeared in a bug report, would I mind?" If you would mind, it is not an output.
Every arrow in the picture above is a dependency: the consumer cannot plan until the producer's outputs exist. A build order is any ordering where each stack comes after everything it reads. (Computer science calls that a topological order; for a handful of stacks you can just read it off the picture.) Two rules follow.
Why the reverse? Because a consumer holds things that sit inside the producer's things. In the cloud, a network cannot be deleted while a server is still attached to it, and the provider refuses with an error (the exact wording varies by provider; est.). In the free lab the failure is different but just as real: the consumer reads the producer's outputs on every plan, including the plan that destroys it. If the producer is gone, the consumer can no longer even plan its own destruction, and you are stuck with resources nothing can remove. You will make this happen on purpose in Exercise 5.
A destroy that reports success is a claim. The evidence is a list that comes back empty. To make that list possible, every resource must carry something a script can search for:
00-foundation) and as the lab does (00-tag). Later stacks read it instead of inventing their own spelling.Cost has to be visible per stack, or nobody sees which stack is the expensive one.
cost.json lists the machines a stack plans, and scripts/cost_check.py prices each from docs/cost-prices.json, adds them up per cloud and fails if the sum goes over the approved figure, if a stack directory has no manifest, if an unpriced billable resource type appears, or if a size is missing from the price table. The gate reads source code; it does not see what is actually running. See Cost and CI, tests and the cost gate.This section is a tour. Nothing here is run: the project's stacks are locked, and every Spacelift change needs the maintainer's confirmation.
stacks/00-foundation (project, baseline tag, VPC, baseline firewall), stacks/10-access (the connector droplets and the Twingate objects) and stacks/20-telemetry (the logging and metrics paths), plus stacks/aws/ for the AWS twin. The numbers match the build stages in the Roadmap; the roadmap names 50-edge for a planned public edge, so the numbers 30 and 40 are free for the workload and dashboard stages that have no directory yet. Only 00 and 10 have ever been applied for real..spacelift/config.yml listing only the secrets that stack may load, and tests that fail closed on that file. See Spacelift.cost.json per stack and refuses a stack directory without one.docs/golden-addresses/00-foundation.json, 10-access.json and 20-telemetry.json list every resource address each stack plans, with the attributes that would force a replacement. scripts/plan_noop_check.py takes a saved plan and fails if anything in it is not a no-op, or an address appears that is not in the golden file, or one is missing. That is the check for "I edited a live stack's code, and the default plan must change nothing". The checker is proven in CI against mocked plan JSON; the real gate is a human reading the real plan in Spacelift..spacelift/policies/plan.rego denies any plan that deletes or replaces a protected resource (a VPC, project, firewall, Twingate remote network, or anything tagged protected), so a full teardown needs the exact addresses added to an allowlist in a reviewed pull request and removed again afterwards. Teardown checklist walks through it.20-telemetry, then 10-access, then 00-foundation, then the Spacelift stacks themselves.Everything above scales up, with a few more decisions to make early because they are painful to change later.
<org>-<env>-<region>-<service>. Short, lowercase, no personal names, no account numbers. A script that tears down or audits an environment depends on being able to match names.docs/superpowers/specs/2026-10-22-stack-factory-status.md; it is a gap analysis, not a finished system.prevent_destroy in the code, a plan policy, or the provider itself. This project's policy denies deleting a VPC, project or firewall until the address is on a reviewed allowlist. Fix: remove the protection on purpose, in a reviewed change, then put it back.403 Can not delete default VPCs; see Lessons learned 9). Fix: make another network the default, or forget the resource from state and leave it, and write down that you did.local provider, which writes small text files in a folder you choose. No account, no network except downloading the provider once from the OpenTofu registry.Teardown. If you have never built anything, there is nothing to tear down. Once you have built, this is the whole teardown, and you can run it any time:
cd ~/iac4-lab && ./lab.sh destroy && ./lab.sh check
cd ~ && rm -rf ~/iac4-lab ~/.cache/iac4-plugins
Set-Location $HOME\iac4-lab; .\lab.ps1 destroy; .\lab.ps1 check
Set-Location $HOME; Remove-Item -Recurse -Force $HOME\iac4-lab, $HOME\.cache\iac4-plugins
Safety. The lab writes only below the folder you give it. Nothing is exposed to a network. Use a scratch folder, never a folder with data you care about.
Five stacks, one folder each, built in order and destroyed in reverse. Each stack manages one thing: a text file. The files stand in for cloud resources: a tag, a firewall, a network and two servers. Every file starts with tag=cah-lab, and every stack except the first reads its upstream stacks' outputs and writes what it saw into its file, so you can see the values travel. The state is local, one terraform.tfstate per stack folder. lab.sh builds all, destroys all, and proves emptiness two ways: every state is empty, and a second, independent look (proof.sh) finds no files. The cloud lab swaps in a different second look and keeps the rest.
Save this as setup.sh and run bash setup.sh. It writes everything into ~/iac4-lab (give a folder as an argument to use another) and runs no OpenTofu.
#!/usr/bin/env bash
# setup.sh: write the five-stack practice lab into a scratch folder. Usage: bash setup.sh [FOLDER]
# SPDX-License-Identifier: Apache-2.0
set -euo pipefail
LAB="${1:-$HOME/iac4-lab}"
mkdir -p "$LAB/stacks" "$LAB/world"
LAB="$(cd "$LAB" && pwd)"
# Stack 00 makes the tag every other stack will read.
mkdir -p "$LAB/stacks/00-tag"
cat > "$LAB/stacks/00-tag/main.tf" <<'EOF'
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.5"
}
}
}
variable "name" { type = string }
variable "world" { type = string }
locals {
tag = "cah-lab"
}
resource "local_file" "this" {
filename = "${var.world}/${var.name}.txt"
content = "tag=${local.tag}\nstack=${var.name}\n"
}
output "tag" {
value = local.tag
}
EOF
# Stacks 10 to 40 share one shape: read the stacks they need, write one file.
mkdir -p "$LAB/stacks/_consumer"
cat > "$LAB/stacks/_consumer/main.tf" <<'EOF'
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.5"
}
}
}
variable "name" { type = string }
variable "world" { type = string }
variable "root" { type = string }
variable "needs" {
type = list(string)
validation {
condition = contains(var.needs, "00-tag")
error_message = "Every stack needs 00-tag: it owns the tag."
}
}
# Read-only look at the OUTPUTS of the stacks this one depends on.
data "terraform_remote_state" "up" {
for_each = toset(var.needs)
backend = "local"
config = {
path = "${var.root}/stacks/${each.key}/terraform.tfstate"
}
}
locals {
tag = data.terraform_remote_state.up["00-tag"].outputs.tag
seen = [for k in sort(var.needs) : "${k}=${try(data.terraform_remote_state.up[k].outputs.id, data.terraform_remote_state.up[k].outputs.tag)}"]
}
resource "local_file" "this" {
filename = "${var.world}/${var.name}.txt"
content = "tag=${local.tag}\nstack=${var.name}\n${join("\n", local.seen)}\n"
}
output "id" {
value = local_file.this.id
}
EOF
mk() { # mk NAME NEEDS... (NEEDS are other stack names)
local name="$1"; shift
mkdir -p "$LAB/stacks/$name"
[ "$name" = "00-tag" ] || cp "$LAB/stacks/_consumer/main.tf" "$LAB/stacks/$name/main.tf"
{
printf 'name = "%s"\nworld = "%s"\n' "$name" "$LAB/world"
if [ "$name" != "00-tag" ]; then
printf 'root = "%s"\nneeds = [' "$LAB"
local first=1 n
for n in "$@"; do [ $first = 1 ] || printf ', '; printf '"%s"' "$n"; first=0; done
printf ']\n'
fi
} > "$LAB/stacks/$name/terraform.tfvars"
}
mk 00-tag
mk 10-firewall 00-tag
mk 20-network 00-tag 10-firewall
mk 30-server-a 00-tag 10-firewall 20-network
mk 40-server-b 00-tag 10-firewall 20-network
rm -r "$LAB/stacks/_consumer"
printf '%s\n' 00-tag 10-firewall 20-network 30-server-a 40-server-b > "$LAB/order.txt"
# proof.sh: the second, independent look. Here: is anything left in the world folder?
cat > "$LAB/proof.sh" <<'EOF'
#!/usr/bin/env bash
LAB="$(cd "$(dirname "$0")" && pwd)"
files=$(find "$LAB/world" -type f | wc -l)
printf '%-14s %s file(s) left\n' "world/" "$files"
[ "$files" = 0 ]
EOF
# audit.sh: list everything left, tagged or not.
cat > "$LAB/audit.sh" <<'EOF'
#!/usr/bin/env bash
LAB="$(cd "$(dirname "$0")" && pwd)"
left=0
while IFS= read -r f; do
left=1
if grep -q '^tag=cah-lab$' "$f"; then echo "TAGGED $(basename "$f")"; else echo "UNTAGGED $(basename "$f")"; fi
done < <(find "$LAB/world" -type f | sort)
[ $left = 0 ] && echo "audit: world is empty"
exit $left
EOF
cat > "$LAB/lab.sh" <<'EOF'
#!/usr/bin/env bash
# lab.sh: build all stacks in order.txt, destroy them in reverse, prove nothing remains.
# SPDX-License-Identifier: Apache-2.0
# Usage: ./lab.sh build | destroy | check | cycle N
set -uo pipefail
LAB="$(cd "$(dirname "$0")" && pwd)"
mapfile -t ORDER < "$LAB/order.txt"
export TF_PLUGIN_CACHE_DIR="${TF_PLUGIN_CACHE_DIR:-$HOME/.cache/iac4-plugins}" TF_IN_AUTOMATION=1
mkdir -p "$TF_PLUGIN_CACHE_DIR"
tf() { local s="$1"; shift; tofu -chdir="$LAB/stacks/$s" "$@" -no-color; }
build() {
local s out rc
for s in "${ORDER[@]}"; do
echo "== build $s"
tf "$s" init -input=false >/dev/null || return 1
out=$(tf "$s" apply -auto-approve -input=false 2>&1); rc=$?
echo "$out" | grep -E "^(Apply complete|Error)" || true
[ $rc = 0 ] || { echo "build failed at $s"; return 1; }
done
}
destroy() {
local i r out rc=0
for ((i=${#ORDER[@]}-1; i>=0; i--)); do
echo "== destroy ${ORDER[i]}"
tf "${ORDER[i]}" init -input=false >/dev/null || rc=1
out=$(tf "${ORDER[i]}" destroy -auto-approve -input=false 2>&1); r=$?
echo "$out" | grep -E "^(Destroy complete|Error)" || true
[ $r = 0 ] || { echo "destroy failed at ${ORDER[i]}"; rc=1; }
done
return $rc
}
# statecount STACK [managed]: items in one stack's state. No state file means nothing was ever applied: 0.
# A state file that exists but cannot be read is an error (return 1), never a zero.
statecount() {
local s="$1" out
[ -f "$LAB/stacks/$s/terraform.tfstate" ] || { echo 0; return 0; }
out=$(tf "$s" state list 2>&1) || return 1
if [ "${2:-}" = managed ]; then out=$(printf '%s\n' "$out" | grep -v '^data\.'); fi
printf '%s\n' "$out" | grep -c . || true
}
count() { # managed resources recorded in all states (data sources do not count)
local s total=0 n
for s in "${ORDER[@]}"; do
n=$(statecount "$s" managed) || { echo "state of $s is unreadable" >&2; return 1; }
total=$((total + n))
done
echo "$total"
}
check() { # every state empty, AND the second look (proof.sh) finds nothing
local s n bad=0
for s in "${ORDER[@]}"; do
if n=$(statecount "$s"); then
printf '%-14s %s item(s) in state\n' "$s" "$n"
[ "$n" = 0 ] || bad=1
else
printf '%-14s state UNREADABLE (this proves nothing)\n' "$s"; bad=1
fi
done
bash "$LAB/proof.sh" || bad=1
if [ $bad = 0 ]; then echo "CHECK PASSED: nothing remains"; else echo "CHECK FAILED: something remains"; fi
return $bad
}
cycle() {
local i n="${1:-5}"
for ((i=1; i<=n; i++)); do
echo "######## cycle $i of $n"
build || { echo "cycle $i: build failed"; return 1; }
echo "cycle $i: $(count) resources in state after build"
destroy || { echo "cycle $i: destroy failed"; return 1; }
check || { echo "cycle $i: NOT EMPTY"; return 1; }
done
echo "ALL $n CYCLES CLEAN"
}
case "${1:-}" in
build) build ;; destroy) destroy ;; check) check ;; cycle) cycle "${2:-5}" ;;
*) echo "usage: $0 build|destroy|check|cycle N"; exit 2 ;;
esac
EOF
chmod +x "$LAB/lab.sh" "$LAB/proof.sh" "$LAB/audit.sh"
echo "lab written to $LAB"