Skip to content

Build and Destroy Stack Per Service Part 1 Why and How Stacks Are Split and the Lab Script

github-actions[bot] edited this page Dec 1, 2026 · 3 revisions

Build and destroy a stack per service, part 1: why and how to split, and the lab script

Home > Track 1: Foundations > Build and destroy, part 1: why and how to split, the lab script

Previous: Build and destroy: one stack per service / Next: Build and destroy, part 2: the PowerShell lab and exercises 1 to 4

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/local provider 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 with tofu init and tofu validate against the digitalocean/digitalocean provider 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.

What you will be able to do

  • Say why a bigger environment is split into one stack per service, and name the costs of splitting just as plainly as the benefits.
  • Lay out a repository so each stack has its own folder, its own state and its own cost line.
  • Pass a value from one stack to another (an output read through remote state, a Spacelift stack dependency, or a lookup by tag), and say why a secret is not one of those values.
  • Work out a build order from the dependencies and destroy in exactly the reverse order, and read the error you get when you do not.
  • Tag every resource so that a forgotten one can be found, and say what a tag audit cannot find.
  • Build and destroy five stacks in a loop, and prove with a checker, not with a feeling, that nothing remains.
  • Compute a hard cost budget for a cloud run from the repository's price file before you create anything.
  • Describe how this project does it (numbered stack directories, a cost gate, golden-address tests, a destroy guard) without running anything against locked stacks.

What the wiki already says (and the gap)

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.

Why one stack per service

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.

What splitting costs

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.

What the layout looks like

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.

Layout conventions worth copying

  • One folder per stack, one state per folder. 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.
  • Numbers with gaps. 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.
  • Names carry meaning. This project names resources <layer>-<region>-<role>. The lab's names carry a prefix (cah-lab-) so a script can find everything the lab made.
  • A committed example, an ignored real file. 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.
  • Validation at the edge. Variables reject bad input before a plan touches an API. The lab's consumer stack refuses to plan unless 00-tag is in its needs list.
  • Look up, do not re-create, what exists. A data source finds something that is already there.
  • Only a short, pinned list of outputs. This project has a test that pins the exact list, so adding an output (and perhaps leaking something through it) has to be done on purpose.
  • Provider lock files are committed, so every run uses the same provider build.
  • A cost manifest per stack (cost.json here), read by the cost gate.
  • Tests that need no account. Each stack has tests/*.tftest.hcl files with mocked providers, so CI proves the shape for free.

Passing values between stacks

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.

Build order and reverse destroy order

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.

  1. Build with the dependencies first.
  2. Destroy in exactly the reverse: the consumers first, the producers last.

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.

Tag everything, so teardown can be proven

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:

  • A tag or label (a short text attached to a resource) naming the environment and the stack, and a name prefix as a second handle. Use both, because not every resource type takes tags. DigitalOcean's documentation says tags apply to droplets "and other DigitalOcean resources", but I did not check which types, so confirm each type you use (est.).
  • A tag is applied at creation, in the same code that creates the resource. A tag added later by hand is a tag somebody has to remember.
  • Put the tag in the first stack, as this project does (a baseline tag in 00-foundation) and as the lab does (00-tag). Later stacks read it instead of inventing their own spelling.
  • A tag is not a proof by itself. It lets a script ask "show me everything with this tag", and the answer proves something only if nothing is untagged. Exercise 6 shows the gap.

Cost counters: a number per stack, and one for the whole

Cost has to be visible per stack, or nobody sees which stack is the expensive one.

  • A manifest per stack. This project's 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.
  • A budget before the run. For your own runs, write the arithmetic down first. The cloud lab below ships a small script that reads only the price file.
  • A time counter. Hourly billing means cost is size times time. The cheapest habit is to put a calendar reminder at the time you plan to have destroyed everything.
  • A spend alert. DigitalOcean's documentation says a spend alert budget "is not a spending cap and does not limit how much you can use". An alert tells you after the money is spent; the destroy is what stops it.

How this project does it

This section is a tour. Nothing here is run: the project's stacks are locked, and every Spacelift change needs the maintainer's confirmation.

  • Stage directories. 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.
  • One Spacelift stack per directory, one explicit stanza per stack in .spacelift/config.yml listing only the secrets that stack may load, and tests that fail closed on that file. See Spacelift.
  • Outputs flow by stack dependency, not remote state; see above.
  • The cost gate reads one cost.json per stack and refuses a stack directory without one.
  • Golden-address tests. 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.
  • A destroy guard. The plan policy .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.
  • Reverse destroy order, written down. 20-telemetry, then 10-access, then 00-foundation, then the Spacelift stacks themselves.

If you are terraforming an entire infrastructure

Everything above scales up, with a few more decisions to make early because they are painful to change later.

  • Environments. Keep development, staging and production apart with separate state and separate accounts or projects, not only a variable that says which. A shared account means a shared blast radius and a shared bill. The same code, called with different inputs, builds each environment. The lesson Environments and promotion applies this to the project's own plan for staging.
  • Naming. Pick one scheme and use it everywhere, such as <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.
  • Accounts and projects. Use the provider's boundary (a project, a team, an account, an organization) as an access boundary, and put resources in the right one at creation. This project puts everything in one DigitalOcean project created by stack 00.
  • A shared network stack. Networks, shared DNS, logging and identity change rarely and many things depend on them. Give them their own stacks, early in the order, owned by the people who can answer for them, and publish only identifiers.
  • Per-service stacks on top. Each service reads the shared outputs it needs and nothing else. Add services without touching the layers below.
  • A stack factory. When the stack count grows, creating each stack by hand in a console does not scale and invites mistakes. This project's design is one explicit stanza per stack, created from code by a factory repository, with tests that fail closed. The status of that work is in docs/superpowers/specs/2026-10-22-stack-factory-status.md; it is a gap analysis, not a finished system.
  • Who may destroy what. Separate three powers and give them to different roles: plan (read-only, anyone on the team), apply (a reviewer or an approval step), destroy (fewest people, with a second pair of eyes for anything shared or production). Turn on the platform's deletion protection where it exists, mark long-lived resources so a policy can refuse to delete them, and keep destroy-capable credentials out of the places that run on every pull request.
  • Tag policy and cost reports. Require tags at creation where the platform can enforce it (some cloud providers have organization-wide tag policies; check yours, est.), and read a cost report grouped by tag or by project at least monthly. Both are in the defend step below.
  • Moving from one big stack to many. Do it in small steps, one service at a time, with a no-op plan as the acceptance test. This project's golden-address file is exactly that test.

Lessons-learned: what makes a destroy fail or leave a bill

  1. A dependency blocks the destroy. A network with a server still attached, a firewall still referenced, a stack whose producer is already gone. Fix: destroy in reverse build order, and read the plan.
  2. A protected resource refuses. Deletion protection, 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.
  3. A default resource cannot be deleted. DigitalOcean refuses to delete a VPC that is a region's default (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.
  4. Volumes, snapshots, reserved addresses and backups outlive the machine. DigitalOcean's documentation says destroying a droplet does not destroy its automated backups (they expire after four weeks) and that associated snapshots and volumes are only destroyed if you ask. Fix: list them after every destroy.
  5. State is left behind. A destroyed stack leaves a state file that is empty but present. Anything that reads that state, as the lab's consumers do, now sees outputs that are not there. Fix: destroy consumers first, and delete the state storage only after proving the stack is empty.
  6. Things made by hand are in no state. No destroy touches them and no cost gate saw them. Fix: a tag audit, an inventory of the whole account, and the discipline of not creating things in a console.
  7. A powered-off machine still bills. DigitalOcean's documentation says bundled-plan droplets that are powered off are still billed, because the compute resources stay reserved; billing ends when you destroy. Fix: destroy, do not stop.
  8. Billing outlives the resource on the page. Usage data lags, the invoice comes at month end, and a minimum charge applies even to a droplet destroyed within a minute. Fix: look again the next day.
  9. The credential was revoked too early. Revoking the token before the destroy leaves a run with nothing to authenticate with. Fix: destroy, prove zero, then revoke (the order in Teardown checklist).
  10. Destroying in the wrong account. The same code run with the wrong token tears down the wrong thing. Fix: before a destroy, check which account the token belongs to, and use a separate account or project for experiments.

Free path: five stacks in a scratch folder

Cost and teardown (read first)

  • Cost. Nothing. The lab uses the 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.

What the lab is

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.

Step 0: write the lab

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"

Where you are: Home > Track 1: Foundations > Build and destroy, part 1: why and how to split, the lab script

Previous: Build and destroy: one stack per service / Next: Build and destroy, part 2: the PowerShell lab and exercises 1 to 4

In this track: Track 1: Foundations, 55 pages

Related pages:

Home | Contents | Reading order | Why this exists | Give feedback

Core path: read in this order (21)
  1. Start here if you are new
  2. What is the cloud
  3. Networking basics
  4. Identity, secrets, zero trust
  5. Infrastructure as code
  6. Git and pull requests
  7. Containers and Docker (optional)
  8. How money works
  9. Enterprise habits
  10. Architecture overview
  11. Why ZTNA and not a VPN
  12. Twingate
  13. DigitalOcean network and firewalls
  14. Droplet hardening
  15. OpenTofu, stacks and modules
  16. Spacelift
  17. Doppler and secrets
  18. CI, tests and the cost gate
  19. Threat model
  20. Lessons learned
  21. Roadmap
Track 1: Foundations (55)
OS and Linux, git and the terminal (14)
Networking (5)
Identity and secrets (7)
Infrastructure as code (8)
Web hosting (5)
Security tools and threat modeling (8)
Digital forensics (2)
Track 2: Defend and detect (46)
Network and host defense (9)
Detection and monitoring (14)
Digital forensics (3)
Device and credential security (1)
Track 3: Privacy, anonymity and cryptocurrency (20)
Cryptography and privacy (4)
Tor, I2P, VPN and browsing (9)
Cryptocurrency (6)
Radio and off-grid (1)
Track 4: GRC and law (9)
GRC, privacy law and data governance (4)
Continuity, backups and recovery (4)
Track 5: Other clouds and enterprise practice (16)
Other clouds (10)
Enterprise practice (6)
How this project runs (16)
Stage guides and design (12)
Project process (4)
Reference (18)

Clone this wiki locally