Chapter 02: Infrastructure as Code (IaC)
Why This Chapter Exists
In production, infrastructure mistakes are expensive and fast-moving. IaC is not only about automation speed. It is about:
- repeatability
- reviewability
- rollback paths
- controlled blast radius
This chapter introduces a guardrails-first Terraform workflow for Kubernetes platforms.
Learning Objectives
By the end of this chapter, learners can:
- explain module boundaries and Terraform folder structure in this repo
- run a safe
plan -> review -> applyworkflow - explain why remote state and locking are non-negotiable in team environments
- detect drift and decide whether to reconcile or rollback
- execute safe destroy practices with explicit scope checks
Repo Mapping
Platform repository references:
- infra/terraform/hcloud_cluster
- infra/terraform/kind_cluster
- scripts/guard-terraform-plan.sh
- .pre-commit-config.yaml
- scripts/terraform-validate.sh
- scripts/terraform-security.sh
- scripts/flux-kustomize-validate.sh
- Chapter 02 Review Checklist
- Chapter 02 Drift Playbook
- Hetzner cluster guide
Core Concepts
- Terraform structure and modules
- root configuration should stay thin and readable
- provider/module versions must be pinned
- reusable logic belongs in modules, not copy/paste blocks
- Remote state and locking
- shared state enables team collaboration
- locking prevents concurrent apply corruption
- backend config is part of production reliability
- IAM and RBAC principles
- least privilege by default
- separate read/plan/apply responsibilities
- no broad credentials for automation or AI tooling
- Drift detection
- drift = actual infra != declared infra
- detect drift before making unrelated changes
- never hide drift by batching many changes together
- Safe destroy
- destroy is valid, but only with explicit scope
- always verify workspace, targets, and dependency impact
- create a rollback/recreate plan before destructive actions
Chapter Flow
- Read this chapter and
lab.md. - Install and run local hooks:
make install-hooks && pre-commit run --all-files. - Run the lab with guardrail scripts.
- Validate expected outputs and complete
quiz.md.
Pre-Commit Guardrails for IaC
Before Terraform changes are committed, hooks enforce:
terraform fmt -recursive -diff -checkscripts/terraform-validate.shscripts/terraform-security.shscripts/flux-kustomize-validate.sh(for anyflux/**manifest changes in the same PR)
These checks reduce noisy reviews and block unsafe IaC changes before they reach CI/apply workflows.
Anti-Patterns to Avoid
- Running
terraform applywithout reviewedplan. - Applying from stale plan output.
- Sharing one credential set across all environments.
- Using destroy in ambiguous context.
Next Chapter
Continue with Chapter 03 (Secrets Management with SOPS).