Build-and-Destroy-Stack-Per-Service-Part-2-The-PowerShell-Lab-and-Exercises-1-to-4.md 16 KB

Build and destroy a stack per service, part 2: the PowerShell lab and exercises 1 to 4

On this page:

Part 2 of 4 of Build and destroy a bunch: one stack per service: The PowerShell version of the lab, then Exercises 1 to 4: predicting, building, destroying and five full cycles.

Previous: Why and how to split, and the lab script / Next: Exercises 5 to 8 and the cloud lab

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.

Free path, continued: the PowerShell lab and exercises 1 to 4 (from the Free path section of the original page)

The PowerShell version writes the same files (est.: not run). Save it as setup.ps1 and run it with .\setup.ps1. If PowerShell refuses to run a script, see your execution policy in Microsoft's documentation, and run it for one session only.

# setup.ps1: write the five-stack practice lab into a scratch folder. Usage: .\setup.ps1 [-Lab FOLDER]
# SPDX-License-Identifier: Apache-2.0
param([string]$Lab = "$HOME\iac4-lab")
$ErrorActionPreference = 'Stop'
New-Item -ItemType Directory -Force "$Lab\stacks", "$Lab\world" | Out-Null
$Lab = (Resolve-Path $Lab).Path
$Fwd = $Lab -replace '\\', '/'   # OpenTofu is happy with forward slashes on Windows

# Stack 00 makes the tag every other stack will read.
$TagTf = @'
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
}
'@

# Stacks 10 to 40 share one shape: read the stacks they need, write one file.
$ConsumerTf = @'
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
}
'@

function New-Stack([string]$Name, [string[]]$Needs) {
    New-Item -ItemType Directory -Force "$Lab\stacks\$Name" | Out-Null
    $tf = if ($Name -eq '00-tag') { $TagTf } else { $ConsumerTf }
    Set-Content -Path "$Lab\stacks\$Name\main.tf" -Value $tf -Encoding ascii
    $vars = @("name  = `"$Name`"", "world = `"$Fwd/world`"")
    if ($Name -ne '00-tag') {
        $list = ($Needs | ForEach-Object { "`"$_`"" }) -join ', '
        $vars += "root  = `"$Fwd`""
        $vars += "needs = [$list]"
    }
    Set-Content -Path "$Lab\stacks\$Name\terraform.tfvars" -Value $vars -Encoding ascii
}
New-Stack '00-tag' @()
New-Stack '10-firewall' @('00-tag')
New-Stack '20-network' @('00-tag', '10-firewall')
New-Stack '30-server-a' @('00-tag', '10-firewall', '20-network')
New-Stack '40-server-b' @('00-tag', '10-firewall', '20-network')

Set-Content "$Lab\order.txt" @('00-tag', '10-firewall', '20-network', '30-server-a', '40-server-b') -Encoding ascii

# proof.ps1: the second, independent look. Here: is anything left in the world folder?
Set-Content "$Lab\proof.ps1" -Encoding ascii -Value @'
$files = @(Get-ChildItem "$PSScriptRoot\world" -Recurse -File).Count
"{0,-14} {1} file(s) left" -f 'world/', $files
exit ([int]($files -ne 0))
'@

# audit.ps1: list everything left, tagged or not.
Set-Content "$Lab\audit.ps1" -Encoding ascii -Value @'
$left = 0
Get-ChildItem "$PSScriptRoot\world" -Recurse -File | Sort-Object Name | ForEach-Object {
    $left = 1
    if (Select-String -Path $_.FullName -Pattern '^tag=cah-lab$' -Quiet) { "TAGGED    $($_.Name)" } else { "UNTAGGED  $($_.Name)" }
}
if ($left -eq 0) { 'audit: world is empty' }
exit $left
'@

Set-Content "$Lab\lab.ps1" -Encoding ascii -Value @'
# lab.ps1: build all stacks in order.txt, destroy them in reverse, prove nothing remains.
# Usage: .\lab.ps1 build | destroy | check | cycle [N]
param([Parameter(Position = 0)][string]$Action = '', [Parameter(Position = 1)][int]$N = 5)
$Lab = $PSScriptRoot
$Order = @(Get-Content "$Lab\order.txt" | Where-Object { $_ })
if (-not $env:TF_PLUGIN_CACHE_DIR) { $env:TF_PLUGIN_CACHE_DIR = "$HOME\.cache\iac4-plugins" }
New-Item -ItemType Directory -Force $env:TF_PLUGIN_CACHE_DIR | Out-Null
$env:TF_IN_AUTOMATION = '1'

function Tf([string]$Stack, [string[]]$More) { & tofu "-chdir=$Lab/stacks/$Stack" @More '-no-color' }

function Build {
    foreach ($s in $Order) {
        "== build $s"
        Tf $s @('init', '-input=false') | Out-Null
        if ($LASTEXITCODE -ne 0) { "build failed at $s"; return $false }
        $out = Tf $s @('apply', '-auto-approve', '-input=false') 2>&1
        $out | Select-String '^(Apply complete|Error)' | Out-Host
        if ($LASTEXITCODE -ne 0) { "build failed at $s"; return $false }
    }
    return $true
}

function Destroy {
    $ok = $true
    for ($i = $Order.Count - 1; $i -ge 0; $i--) {
        $s = $Order[$i]
        "== destroy $s"
        Tf $s @('init', '-input=false') | Out-Null
        $out = Tf $s @('destroy', '-auto-approve', '-input=false') 2>&1
        $out | Select-String '^(Destroy complete|Error)' | Out-Host
        if ($LASTEXITCODE -ne 0) { "destroy failed at $s"; $ok = $false }
    }
    return $ok
}

# State-Count STACK: items in one state. No state file means nothing was applied: 0.
# A state file that exists but cannot be read returns -1 (an error), never 0.
function State-Count([string]$Stack, [bool]$ManagedOnly = $false) {
    if (-not (Test-Path "$Lab\stacks\$Stack\terraform.tfstate")) { return 0 }
    $out = Tf $Stack @('state', 'list') 2>&1
    if ($LASTEXITCODE -ne 0) { return -1 }
    $items = @($out | Where-Object { $_ })
    if ($ManagedOnly) { $items = @($items | Where-Object { $_ -notmatch '^data\.' }) }
    return $items.Count
}

function Count-Managed { # managed resources in all states (data sources do not count)
    $total = 0
    foreach ($s in $Order) { $total += [Math]::Max(0, (State-Count $s $true)) }
    return $total
}

function Check { # every state empty, AND the second look (proof.ps1) finds nothing
    $bad = $false
    foreach ($s in $Order) {
        $n = State-Count $s
        if ($n -lt 0) { "{0,-14} state UNREADABLE (this proves nothing)" -f $s; $bad = $true; continue }
        "{0,-14} {1} item(s) in state" -f $s, $n
        if ($n -ne 0) { $bad = $true }
    }
    & "$Lab\proof.ps1"
    if ($LASTEXITCODE -ne 0) { $bad = $true }
    if ($bad) { 'CHECK FAILED: something remains' } else { 'CHECK PASSED: nothing remains' }
    return (-not $bad)
}

switch ($Action) {
    'build'   { if (Build) { exit 0 } else { exit 1 } }
    'destroy' { if (Destroy) { exit 0 } else { exit 1 } }
    'check'   { if (Check) { exit 0 } else { exit 1 } }
    'cycle'   {
        for ($i = 1; $i -le $N; $i++) {
            "######## cycle $i of $N"
            if (-not (Build)) { "cycle $i`: build failed"; exit 1 }
            "cycle $i`: $(Count-Managed) resources in state after build"
            if (-not (Destroy)) { "cycle $i`: destroy failed"; exit 1 }
            if (-not (Check)) { "cycle $i`: NOT EMPTY"; exit 1 }
        }
        "ALL $N CYCLES CLEAN"
    }
    default   { 'usage: .\lab.ps1 build|destroy|check|cycle [N]'; exit 2 }
}
'@
Write-Output "lab written to $Lab"

Look at what you got. The producer stack is short, and the other four are one file copied four times with different terraform.tfvars:

cd ~/iac4-lab
cat stacks/30-server-a/terraform.tfvars
Set-Location $HOME\iac4-lab
Get-Content .\stacks\30-server-a\terraform.tfvars

You will see the stack's name, the world folder, the root folder and needs = ["00-tag", "10-firewall", "20-network"]. The needs list is the dependency list from the picture, in data.

Exercise 1: predict before you build

Predict. Without running anything, write down: (a) how many resources the five states will hold after a full build; (b) which stack's file will contain the line 10-firewall= and what comes after the equals sign; (c) what ./lab.sh check will say right now, before any build.

Do.

cd ~/iac4-lab
./lab.sh check; echo "exit=$?"
Set-Location $HOME\iac4-lab
.\lab.ps1 check; "exit=$LASTEXITCODE"

Check. Before any build there are no states yet, so each stack shows 0 item(s) in state, the world folder shows 0 file(s) left, and the check prints CHECK PASSED: nothing remains and exits 0. That is the baseline: a checker you have only ever seen pass proves nothing, so you will see it fail in Exercise 3 and Exercise 6. (a) is 5, one local file per stack; the remote-state lookups are data sources and are not counted. (b) The files for 20-network, 30-server-a and 40-server-b, each followed by the firewall file's ID (a long hexadecimal string; yours will differ).

Undo. Nothing was created.

Exercise 2: build all five, in order

Predict. Which stack must be built first, and what happens if you try to plan 30-server-a before 00-tag exists?

Do.

cd ~/iac4-lab
./lab.sh build
cat world/40-server-b.txt
Set-Location $HOME\iac4-lab
.\lab.ps1 build
Get-Content .\world\40-server-b.txt

Check. Five lines of the form == build <stack> each followed by Apply complete! Resources: 1 added, 0 changed, 0 destroyed. (the first run also downloads the provider and takes longer). The file looks like this; the two IDs will differ:

tag=cah-lab
stack=40-server-b
00-tag=cah-lab
10-firewall=1d71d8f7a40d90e5f49f14de224b2b0133266fbd
20-network=c1e113a77d9a86f4de352c5581aa9745f28c0ac1

Those last three lines are the cross-stack values. 00-tag=cah-lab is the producer's output; the other two are IDs from the stacks it read. Run ./lab.sh build a second time: every stack says 0 added, because nothing changed. A second run that changes nothing is a property worth wanting from every stack. For the answer to the predict question: if you try to plan 30-server-a first, its terraform_remote_state looks for state files that are not there and the plan fails with Error: Unable to find remote state (what OpenTofu 1.12.6 printed on 2026-10-22).

Undo. The next exercise destroys it.

Exercise 3: destroy all five, in reverse, and prove it

Predict. In what order will the stacks be destroyed? After the destroy, will the folders stacks/*/terraform.tfstate still exist?

Do.

./lab.sh destroy
./lab.sh check; echo "exit=$?"
ls stacks/00-tag
.\lab.ps1 destroy
.\lab.ps1 check; "exit=$LASTEXITCODE"
Get-ChildItem .\stacks\00-tag

Check. The destroy goes 40-server-b, 30-server-a, 20-network, 10-firewall, 00-tag, each reporting Destroy complete! Resources: 1 destroyed. Then the check prints:

00-tag         0 item(s) in state
10-firewall    0 item(s) in state
20-network     0 item(s) in state
30-server-a    0 item(s) in state
40-server-b    0 item(s) in state
world/         0 file(s) left
CHECK PASSED: nothing remains

and exits 0. The state files still exist (terraform.tfstate and a .backup): they are empty, which is the hazard in lessons-learned item 5. An empty state is not the same as no state; that is why the checker asks for resources, not for the absence of a file.

Undo. Nothing to undo; this was the undo. Build again when you need to.

Exercise 4: five full cycles

A loop is where this becomes a habit. One cycle is: build all, count what is in state, destroy all, run the checker. Any red stops the loop.

Predict. How many resources will the count show after each build, and will the fifth cycle be any different from the first?

Do.

cd ~/iac4-lab
./lab.sh cycle 5
Set-Location $HOME\iac4-lab
.\lab.ps1 cycle 5

Check. For each of the five cycles you see cycle N: 5 resources in state after build, then the destroy, then CHECK PASSED: nothing remains, and the last line is ALL 5 CYCLES CLEAN. On the author's machine the five cycles took about 13 seconds in all once the provider was cached. If a cycle fails, the script stops there and tells you which one; do not start another until you can explain it.

Undo. The loop ends with everything destroyed. Run ./lab.sh check to see it for yourself.