10.1 · Definition — declarative beats imperative
Definition. Infrastructure as Code is the practice of declaring the desired shape of infrastructure in machine-readable, version-controlled files and letting an automated engine reconcile reality to that declaration. The first widely cited use of the term is in Infrastructure as Code by Kief Morris (O'Reilly, 1st ed. 2016).
| Style | Question it answers | Examples | Trade-off |
|---|---|---|---|
| Imperative | "What steps do I run?" | Bash, AWS CLI scripts, early Chef recipes. | Drift-prone, hard to re-run. |
| Declarative | "What end-state do I want?" | Terraform, Bicep, CloudFormation, Crossplane. | Engine has to compute the plan — opaque when wrong. |
| Programmatic-declarative | "Declarative via a real language." | Pulumi, AWS CDK, CDKTF, cdk8s. | Best ergonomics; risk of writing imperative loops that look declarative. |
destroy the workspace, re-apply, and end up with an identical environment — it's IaC. If a recovery requires "Step 6: click the console" — it isn't.10.2 · The IaC landscape (2026)
| Tool | Vendor / origin | Language | Scope | Status |
|---|---|---|---|---|
| Terraform | HashiCorp (2014) | HCL | Multi-cloud, >3,000 providers. | BSL 1.1 since v1.6 (Aug 2023). |
| OpenTofu | Linux Foundation (Jan 2024) | HCL | Drop-in TF fork. | MPL 2.0; v1.8 (2024), v1.9+ adds early-eval, S3 native locking. |
| Pulumi | Pulumi Corp (2018) | TS/JS, Python, Go, .NET, Java, YAML | Multi-cloud + K8s. | Apache-2.0; ESC for secrets/config. |
| AWS CDK | AWS (2019) | TS, Python, Java, .NET, Go | Synthesises CloudFormation. | v2 GA Dec 2021. |
| CDKTF | HashiCorp + AWS (2022) | TS, Python, Java, .NET, Go | CDK syntax → Terraform JSON. | v0.20 (2024). |
| Azure Bicep | Microsoft (2020) | Bicep DSL | ARM-only; transpiles to ARM JSON. | v0.27+ (2025). |
| CloudFormation | AWS (2011) | YAML/JSON | AWS only. | Native; StackSets multi-account. |
| GCP Config Connector / Config Controller | K8s YAML (CRDs) | GCP via K8s controllers. | Anthos add-on. | |
| Crossplane | Upbound (CNCF graduated Nov 2024) | K8s YAML | K8s-native universal control plane. | v1.16 (2025). |
| Ansible | Red Hat (2012) | YAML | Provisioning + CM (declarative-ish). | See Ch 11. |
| SST | SST.dev (2021) | TS | Serverless on AWS, Pulumi-backed. | v3 "Ion" (2024). |
| Winglang | Wing Cloud (2023) | Wing | Cloud-oriented language, sim-first. | Pre-1.0 in 2026. |
10.3 · State management
The state file is the truth Terraform/OpenTofu uses to map declared resources to cloud IDs. It must be remote, locked, and backed up.
| Backend | Locking | Cost | Notes |
|---|---|---|---|
| S3 + DynamoDB (TF) / S3 native (OpenTofu 1.10+) | DynamoDB row / S3 conditional writes | $$ | Default AWS pattern; enable versioning + SSE-KMS. |
| GCS | Object generation | $ | Built-in; no helper service. |
| azurerm | Blob lease | $ | Use storage account with RA-GRS. |
| Consul / Postgres | Native | — | On-prem patterns. |
| HCP Terraform / Terraform Cloud | Managed | $$$ | Workspaces, run UI, Sentinel, drift detection. |
| Spacelift / Env0 / Scalr | Managed | $$$ | Policy, drift, stack dependencies, OPA-friendly. |
| Atlantis | PR-driven | self-host | OSS; great for GitHub-first orgs. |
terraform.tfstate to git. It contains secrets in plaintext, breaks on parallel runs, and corrupts under merges.10.4 · Modules & composability
Terraform / OpenTofu
Modules — folder of .tf files exposing variables and outputs. Published to the public registry (registry.terraform.io / opentofu.org) or private (TFC / Spacelift / S3 / Git).
Pulumi
Component Resources — classes that compose other resources; published as packages (npm/PyPI/NuGet).
AWS CDK
Constructs — L1 (raw CFN), L2 (opinionated), L3 (patterns). Construct Hub.
Bicep
Modules registry on ACR; br/public alias for the Microsoft catalog.
Crossplane
Compositions + XRDs let platform teams expose a typed claim (XPostgreSQLInstance) implemented by N managed resources.
10.5 · Drift detection & remediation
Drift is when reality (the cloud) and intent (the code) disagree — someone clicked the console, or a sibling automation mutated a tag. Detecting it early avoids "the apply that nukes prod".
- terraform plan in CI on a schedule — exit code 2 means drift. Trivial & free.
- driftctl (Snyk, archived 2023 but still usable) — out-of-band resources, not just drift in state.
- HCP Terraform / Spacelift / Env0 — managed drift detection runs, with notify-only or auto-remediate modes.
- AWS Config / Azure Policy / GCP Asset Inventory — cloud-native drift telemetry, complementary not replacement.
10.6 · Policy-as-code (the IaC firewall)
| Engine | Language | Runs at | Best for |
|---|---|---|---|
| HashiCorp Sentinel | Sentinel DSL | HCP Terraform / Vault Enterprise | Mandated policies inside TFC. |
| OPA / Conftest | Rego | CLI, CI, K8s admission | Vendor-neutral, multi-domain policy. |
| Checkov (Prisma Cloud) | Python YAML rules | CLI, CI | Out-of-box rules for TF/CFN/Bicep/K8s. |
| tfsec (now Trivy) | — | CLI, CI | TF-only; merged into Aqua Trivy in 2023. |
| Terrascan (Accurics → Tenable) | Rego | CLI, CI, admission | Wide coverage; CIS profiles. |
| KICS (Checkmarx) | Rego-like | CLI, CI | TF, K8s, Docker, CFN, Ansible, Helm. |
| CloudFormation Guard (cfn-guard) | Guard DSL | CLI, CI | AWS-native, lightweight. |
| AWS Config Rules | Lambda / Guard | Runtime | Reactive, not pre-deploy. |
10.7 · Testing IaC
- Terratest (Gruntwork, Go) — spin real infra, assert, tear down. Slow but high-fidelity.
- terraform test — built-in HCL test framework since TF v1.6 / OpenTofu 1.7.
- kitchen-terraform — Ruby Test-Kitchen integration; legacy but still in use.
- pytest-tf, tftest — Python harnesses for plan-output assertions.
- Pulumi unit tests — language-native (Jest, pytest) with mocks.
- Snapshot testing — compare rendered CFN/ARM JSON to checked-in golden file (CDK has
Template.fromStack). - Ephemeral preview environments — TFC workspaces / Spacelift stacks / Pulumi review stacks per PR.
10.8 · Secrets in IaC
.tf / .bicep / .yaml file, in state, or in CI logs.- Use the vault / aws_secretsmanager_secret_version / azurerm_key_vault_secret / google_secret_manager_secret_version data source — pull at apply time.
- Mark Terraform variables
sensitive = trueso values are redacted from plan output. - Enable state-file encryption (S3 SSE-KMS, GCS CMEK, Terraform Cloud encryption at rest).
- Pulumi ESC & HCP Vault Secrets centralise dynamic config & rotate.
- For ephemeral CI credentials, use OIDC federation (see Ch 12) — no static keys in repo or CI variables.
10.9 · IaC for Kubernetes
| Approach | Pros | Cons |
|---|---|---|
Helm via helm_release (TF provider) or chart in Argo CD | Huge chart ecosystem. | Templating is fragile. |
| Kustomize via Argo CD / Flux Kustomization | No templating; PR-friendly diffs. | Hard to parameterise deeply. |
| Crossplane Compositions | K8s-native, claims are typed APIs. | Steep learning curve. |
| Terraform K8s / Kubernetes provider | One tool for cloud + cluster. | Drift if anyone applies kubectl. |
| Argo CD + Terraform Operator | GitOps for infra (Terraform CRD reconciled by Argo). | Two reconcilers; need to design ownership. |
10.10 · The "platform" of IaC
Raw HCL/YAML is a power tool, not a product. Platform teams hide it behind a self-service layer:
Backstage Scaffolder
Spotify-OSS template engine — "new microservice" → repo + pipeline + IaC stack in one click.
Score
Workload-spec abstraction (CNCF sandbox 2023) — developers write Score files, platform converts to TF/Helm/etc.
Humanitec
Platform Orchestrator that picks the right module per environment.
Port / Cortex / OpsLevel
Internal Developer Portals — surface IaC actions as buttons.
10.11 · Anti-patterns
| Anti-pattern | Why it hurts | Fix |
|---|---|---|
| Clickops after apply | Permanent drift; next apply destroys hand-clicked resources. | SCP / Azure Policy blocking write in console; quarterly drift report. |
| Mega-module (the "everything" module) | Blast radius = entire org; long plans. | Slice by lifecycle (network, IAM, app). |
| No state backups | One corrupt push and recovery is forensic. | Versioned bucket, daily snapshot to cold storage. |
| Shared workspace per env | Prod & staging in the same state; one bad apply = both gone. | One workspace per (stack × env). |
| Manual provider upgrades | Sudden breaking changes appear in unrelated PRs. | Renovate / Dependabot + pinned versions + lockfile (.terraform.lock.hcl). |
Secrets in tfvars | End up in git history forever. | Dynamic data sources + OIDC + Vault. |
10.12 · Self-check
terraform.tfstate to git dangerous?