LOOP · The DevOps Codex
Ch 10 · Infrastructure as Code
Chapter 10 · Provisioning

Infrastructure as Code — infra you can diff, review, revert

Infrastructure as Code (IaC) treats every cloud resource — VPCs, IAM roles, databases, DNS — as version-controlled source. A reconciler turns those files into API calls, plans the diff, and applies it. This chapter compares the eight serious tools of 2026, the state & locking story, modules and policies, drift, testing, secrets, and the anti-patterns that will burn an org.

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).

StyleQuestion it answersExamplesTrade-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.
Litmus test
If you can 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)

ToolVendor / originLanguageScopeStatus
TerraformHashiCorp (2014)HCLMulti-cloud, >3,000 providers.BSL 1.1 since v1.6 (Aug 2023).
OpenTofuLinux Foundation (Jan 2024)HCLDrop-in TF fork.MPL 2.0; v1.8 (2024), v1.9+ adds early-eval, S3 native locking.
PulumiPulumi Corp (2018)TS/JS, Python, Go, .NET, Java, YAMLMulti-cloud + K8s.Apache-2.0; ESC for secrets/config.
AWS CDKAWS (2019)TS, Python, Java, .NET, GoSynthesises CloudFormation.v2 GA Dec 2021.
CDKTFHashiCorp + AWS (2022)TS, Python, Java, .NET, GoCDK syntax → Terraform JSON.v0.20 (2024).
Azure BicepMicrosoft (2020)Bicep DSLARM-only; transpiles to ARM JSON.v0.27+ (2025).
CloudFormationAWS (2011)YAML/JSONAWS only.Native; StackSets multi-account.
GCP Config Connector / Config ControllerGoogleK8s YAML (CRDs)GCP via K8s controllers.Anthos add-on.
CrossplaneUpbound (CNCF graduated Nov 2024)K8s YAMLK8s-native universal control plane.v1.16 (2025).
AnsibleRed Hat (2012)YAMLProvisioning + CM (declarative-ish).See Ch 11.
SSTSST.dev (2021)TSServerless on AWS, Pulumi-backed.v3 "Ion" (2024).
WinglangWing Cloud (2023)WingCloud-oriented language, sim-first.Pre-1.0 in 2026.
License watershed
The BSL relicense of Terraform in Aug 2023 split the community. By 2026 every Fortune 100 with a HashiCorp ELA still uses Terraform; everyone allergic to BSL has moved to OpenTofu. The HCL syntax is identical; the providers register is shared.

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.

BackendLockingCostNotes
S3 + DynamoDB (TF) / S3 native (OpenTofu 1.10+)DynamoDB row / S3 conditional writes$$Default AWS pattern; enable versioning + SSE-KMS.
GCSObject generation$Built-in; no helper service.
azurermBlob lease$Use storage account with RA-GRS.
Consul / PostgresNative—On-prem patterns.
HCP Terraform / Terraform CloudManaged$$$Workspaces, run UI, Sentinel, drift detection.
Spacelift / Env0 / ScalrManaged$$$Policy, drift, stack dependencies, OPA-friendly.
AtlantisPR-drivenself-hostOSS; great for GitHub-first orgs.
Never
Never commit 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)

EngineLanguageRuns atBest for
HashiCorp SentinelSentinel DSLHCP Terraform / Vault EnterpriseMandated policies inside TFC.
OPA / ConftestRegoCLI, CI, K8s admissionVendor-neutral, multi-domain policy.
Checkov (Prisma Cloud)Python YAML rulesCLI, CIOut-of-box rules for TF/CFN/Bicep/K8s.
tfsec (now Trivy)—CLI, CITF-only; merged into Aqua Trivy in 2023.
Terrascan (Accurics → Tenable)RegoCLI, CI, admissionWide coverage; CIS profiles.
KICS (Checkmarx)Rego-likeCLI, CITF, K8s, Docker, CFN, Ansible, Helm.
CloudFormation Guard (cfn-guard)Guard DSLCLI, CIAWS-native, lightweight.
AWS Config RulesLambda / GuardRuntimeReactive, not pre-deploy.

10.7 · Testing IaC

unit (mocks)
→
contract (snapshot)
→
integration (ephemeral env)
→
policy gates
  • 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

Rule zero
No secret ever appears in plaintext in a .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 = true so 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

ApproachProsCons
Helm via helm_release (TF provider) or chart in Argo CDHuge chart ecosystem.Templating is fragile.
Kustomize via Argo CD / Flux KustomizationNo templating; PR-friendly diffs.Hard to parameterise deeply.
Crossplane CompositionsK8s-native, claims are typed APIs.Steep learning curve.
Terraform K8s / Kubernetes providerOne tool for cloud + cluster.Drift if anyone applies kubectl.
Argo CD + Terraform OperatorGitOps 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.

developer Backstage / PortScore / claim Platform orchestratorHumanitec / Crossplane cloud APIsvia TF / Pulumi

10.11 · Anti-patterns

Anti-patternWhy it hurtsFix
Clickops after applyPermanent 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 backupsOne corrupt push and recovery is forensic.Versioned bucket, daily snapshot to cold storage.
Shared workspace per envProd & staging in the same state; one bad apply = both gone.One workspace per (stack × env).
Manual provider upgradesSudden breaking changes appear in unrelated PRs.Renovate / Dependabot + pinned versions + lockfile (.terraform.lock.hcl).
Secrets in tfvarsEnd up in git history forever.Dynamic data sources + OIDC + Vault.

10.12 · Self-check

Q1 · Which event most directly produced the OpenTofu fork?
Terraform v1.0 release
HashiCorp's August 2023 BSL relicense
AWS launching CDK
The 2018 Pulumi launch
Q2 · Where does Bicep ultimately get applied?
Terraform engine
Azure Resource Manager (ARM)
Pulumi engine
AWS CloudFormation
Q3 · Why is committing terraform.tfstate to git dangerous?
It bloats the repo
It leaks secrets and corrupts under concurrent runs
Git can't store JSON
Terraform refuses to read it