Repository navigation
Build and Destroy Stack Per Service Part 2 The PowerShell Lab and Exercises 1 to 4
Home > Track 1: Foundations > Build and destroy, part 2: the PowerShell lab and exercises 1 to 4
Previous: Build and destroy, part 1: why and how to split, the lab script / Next: Build and destroy, part 3: exercises 5 to 8 and the cloud lab
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/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.
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.tfvarsSet-Location $HOME\iac4-lab
Get-Content .\stacks\30-server-a\terraform.tfvarsYou 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.
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.
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.txtSet-Location $HOME\iac4-lab
.\lab.ps1 build
Get-Content .\world\40-server-b.txtCheck. 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.
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-tagCheck. 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.
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 5Set-Location $HOME\iac4-lab
.\lab.ps1 cycle 5Check. 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.
Where you are: Home > Track 1: Foundations > Build and destroy, part 2: the PowerShell lab and exercises 1 to 4
Previous: Build and destroy, part 1: why and how to split, the lab script / Next: Build and destroy, part 3: exercises 5 to 8 and the cloud lab
In this track: Track 1: Foundations, 55 pages
- OS and Linux, git and the terminal: Git from zero / The terminal and your first script / Linux for enterprise beginners / First hour on a new system / Patch management and automatic security updates / Red and blue, and choosing your lab OS / Virtual machines and hypervisors: desktop to datacenter / Device firmware security: Intel ME, AMD PSP, MINIX and kernel design / Virtual machines, containers and cloud service models / Kubernetes for beginners / Choosing a container engine: Docker, Podman, Kubernetes, Portainer and Cockpit / Self-hosting AI: Ollama, vLLM and the GPU stack / Windows, Active Directory and macOS / Cron, systemd timers and init scripts versus systemd
- Networking: How a web request works / DNS, Cloudflare and hosting your own website / Subnets, NAT and firewalls by hand / Behind a CDN: real client IPs and OSI basics / IPv6 adoption and handling it safely
- Identity and secrets: APIs and tokens from zero / Hashing, encryption and keys / Secrets from day one / Secrets from day one, part 1: the rules, the tools, the threat model / Secrets from day one, part 2: free lab setup, exercises 1 and 2 / Secrets from day one, part 3: exercises 3 to 5, optional Doppler path / Secrets from day one, part 4: build, break, defend, checkpoint, claims / Password managers and passkeys / Disk and file encryption: VeraCrypt, TrueCrypt, BitLocker, FileVault, LUKS / Enterprise identity: SSO, SAML and OIDC / Hardware security keys: YubiKey, Nitrokey, PIV
- Infrastructure as code: Data formats: JSON, YAML, HCL / OpenTofu from zero / OpenTofu from zero, part 1: concepts, install, exercises 1 and 2 / OpenTofu from zero, part 2: exercises 3 to 6 / OpenTofu from zero, part 3: exercise 7, build and destroy a bunch / OpenTofu from zero, part 4: build, break, defend, checkpoint, claims / OpenTofu plans, state, drift and recovery / Plans, state, drift and recovery, part 1: reading plans and state / Plans, state, drift and recovery, part 2: state, locking and drift exercises / Plans, state, drift and recovery, part 3: moving and losing state / Plans, state, drift and recovery, part 4: the drill and the checkpoint / Ansible: configuration management versus provisioning / Native IaC versus open standards / Spacelift from zero / Build and destroy: one stack per service / Build and destroy, part 1: why and how to split, the lab script / Build and destroy, part 2: the PowerShell lab and exercises 1 to 4 / Build and destroy, part 3: exercises 5 to 8 and the cloud lab / Build and destroy, part 4: Spacelift, defend, claims register / Environments and promotion
- Web hosting: LAMP and LEMP from zero / WordPress and PHP security, WAFs and static sites / Static against dynamic: Hugo, WordPress and recon / WordPress at scale: CDN, WAF, caching and CI / Autoscaling and elasticity
Related pages:
Source for these pages lives in docs/wiki/ and is published by the Wiki workflow on every merge to main. Corrections are welcome as pull requests; edits made in the wiki editor are overwritten on the next publish. Apache-2.0 licensed, see LICENSE and NOTICE in the repository.
Support this project: support.chiefgyk3d.com, or see Home. | Ko-fi
Home | Contents | Reading order | Why this exists | Give feedback
Core path: read in this order (21)
- Start here if you are new
- What is the cloud
- Networking basics
- Identity, secrets, zero trust
- Infrastructure as code
- Git and pull requests
- Containers and Docker (optional)
- How money works
- Enterprise habits
- Architecture overview
- Why ZTNA and not a VPN
- Twingate
- DigitalOcean network and firewalls
- Droplet hardening
- OpenTofu, stacks and modules
- Spacelift
- Doppler and secrets
- CI, tests and the cost gate
- Threat model
- Lessons learned
- Roadmap
Track 1: Foundations (55)
OS and Linux, git and the terminal (14)
- Git from zero · The terminal and your first script · Linux for enterprise beginners (est. steps) · First hour on a new system
- Patch management and automatic security updates · Red and blue, and choosing your lab OS · Virtual machines and hypervisors: desktop to datacenter (draft)
- Device firmware security: Intel ME, AMD PSP, MINIX and kernel design (draft) · Virtual machines, containers and cloud service models · Kubernetes for beginners (draft)
- Choosing a container engine: Docker, Podman, Kubernetes, Portainer and Cockpit (draft) · Self-hosting AI: Ollama, vLLM and the GPU stack (draft)
- Windows, Active Directory and macOS · Cron, systemd timers and init scripts versus systemd (draft)
Networking (5)
Identity and secrets (7)
- APIs and tokens from zero · Hashing, encryption and keys · Secrets from day one · Password managers and passkeys (draft)
- Disk and file encryption: VeraCrypt, TrueCrypt, BitLocker, FileVault, LUKS (draft) · Enterprise identity: SSO, SAML and OIDC
- Hardware security keys: YubiKey, Nitrokey, PIV (draft)
Infrastructure as code (8)
Web hosting (5)
Security tools and threat modeling (8)
- Threats in plain words
- Security tools: Nmap, OpenVAS, Burp, Metasploit
- Threat frameworks: STRIDE, ATT&CK, ATLAS
- Email security
- Threat model exercise
- Threat Dragon exercise
Digital forensics (2)
Track 2: Defend and detect (46)
Network and host defense (9)
- Packet filters compared · IDS and IPS · File integrity and alerting · Rate limiting at every layer · Plan for failure: blast radius and assuming breach
- Attack surface: list, shrink, measure (draft) · Attack surface map: layer by layer (draft) · The DMZ and hardening an internet-facing host (draft)
- DMZ hardening checklist (draft)
Detection and monitoring (14)
- A small example: the enterprise landscape · Logs, SIEM and detection basics · Detection, Wazuh and the landscape (unbuilt) · Wazuh SIEM and data pipelines (est. steps)
- Detecting Tor, I2P and VPN on a network (draft) · Cloud telemetry: what and why (draft) · Multiple sites and identity (draft)
- Telemetry crosses the trust boundary (draft) · Reading a dashboard as an operator (draft) · Grafana basics from a blank page (est. steps) · Grafana dashboards
- Lab: synthetic multi-site monitoring stack · Build your own mini SOC (draft) · Stage 2 home-side runbook (unbuilt)
Digital forensics (3)
- DFIR toolkits and live triage (draft) · Digital forensics foundations (draft) · Network, log and timeline forensics (draft)
Device and credential security (1)
Track 3: Privacy, anonymity and cryptocurrency (20)
Cryptography and privacy (4)
- Cryptography fundamentals (draft) · Privacy, security and anonymity (draft) · Privacy versus security (draft)
- Hardware security modules and building your own with pico2hsm (draft)
Tor, I2P, VPN and browsing (9)
- Tor, I2P and the darknet without the myths (draft) · How a VPN works (draft) · How Tor works in depth (draft) · How I2P works (draft)
- The browsing setups compared (draft) · OPSEC for Tor and I2P (draft) · Hands-on Whonix and Qubes OS (draft) · The darknet landscape: markets, OPSEC and layering (draft)
- Lab: publish a web server as an onion service and an I2P site (draft)
Cryptocurrency (6)
- Blockchain fundamentals (draft) · How Bitcoin works (draft) · How Monero works (draft) · Wallets and key custody (draft)
- Paper wallets and offline key generation (draft) · Running Monero properly (draft)
Radio and off-grid (1)
- Radio and off-grid communication (draft)
Track 4: GRC and law (9)
- The CIA triad (draft)
GRC, privacy law and data governance (4)
- GRC in plain terms (draft) · US privacy law and the patchwork (draft) · Privacy law around the world (draft) · Cross-tenant data flows, governance, retention and DLP
Continuity, backups and recovery (4)
- Business continuity and disaster recovery (draft) · Backups, recovery and patching · Backups deep dive (draft) · RAID: continuity, not a backup (draft)
Track 5: Other clouds and enterprise practice (16)
Other clouds (10)
- Why the clouds differ (draft) · AWS: account preparation (draft) · AWS: the same four pieces (draft) · AWS: where the money goes (draft)
- Azure: account preparation (draft) · Azure: the same four pieces (draft) · Azure: where the money goes (draft) · GCP: account preparation (draft)
- GCP: the same four pieces (draft) · GCP: where the money goes (draft)
Enterprise practice (6)
How this project runs (16)
Stage guides and design (12)
- Fork, private stacks, the pipeline · Labs: break it on purpose · Build it: zero accounts to stage 1 · Variables, tfvars and secrets · Teardown checklist
- Self-hosting: when and why, with SearXNG (draft) · Twingate service accounts in CAH · Zero trust at home: two connectors and failover
- Why not private droplets (yet) (draft) · Why I picked these tools · From commit to pipeline · Trace one change end to end