Andrew Mercer
on this page
Page Covers
This page Workflow: local loop, MRs, reading plans, review, upgrades, docs
HCL development hygiene Code-level conventions: naming, file layout, formatting, linting, typing, comments

Principles

  1. Small changes. One concern per merge request. A plan reviewers can read in two minutes gets reviewed properly; a 400-resource plan gets rubber-stamped.
  2. Plans are the review artifact. Code shows intent; the plan shows consequences. Review both.
  3. Humans review, pipelines apply. No laptop applies to shared environments.
  4. Everything versioned and pinned. Terraform, providers, modules, CI images, scanners.
  5. Make the right thing the easy thing. Templates, pre-commit, CI checks and shared modules do more than guidelines.

Local development loop

terraform fmt -recursive          # format
terraform init -backend=false     # providers/modules, no state (for validate/test)
terraform validate                # syntax and types
tflint --recursive                # lint
terraform test                    # module tests (mocked where possible)
terraform plan                    # against dev with your read-only identity

Wrap it in a task runner so everyone runs the same thing:

.PHONY: fmt lint test plan check

fmt:
    terraform fmt -recursive

lint:
    terraform init -backend=false -input=false >/dev/null
    terraform validate
    tflint --recursive

test:
    terraform test

check: fmt lint test
    pre-commit run --all-files

(just works equally well if you prefer it.)

Planning locally when CI holds the variables

Shared environments often get credentials and TF_VAR_* values from CI, so a laptop plan fails on missing variables. Options, best first:

  1. Run the plan in CI from your branch. The MR pipeline is the plan. No local secrets needed.
  2. direnv + Key Vault: an .envrc (git-ignored) that pulls non-secret config and your own read-only credentials:

bash # .envrc export ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) export TF_VAR_environment=dev export TF_VAR_alert_webhook=$(az keyvault secret show --vault-name kv-platform-dev \ --name alert-webhook --query value -o tsv)

  1. A committed dev.tfvars with every non-secret value, so only secrets come from the environment.
  2. Mock providers for anything that's really a module test (testing).

Never copy CI service principal secrets to a laptop.

Fast iteration on modules

  • Point a test root at the local module path (source = "../../modules/network") while developing, then switch back to the registry version.
  • With Terragrunt: terragrunt plan --source ../../modules//network (Terragrunt).
  • terraform console to try expressions before writing them into resources.
  • Terraform 1.16: terraform console -scope=module.x to evaluate inside a child module.

Branching and merge requests

  • Trunk-based: short-lived feature branches off main, merged after review and a clean plan. Environments are directories (or tfvars), not branches. Branch-per-environment models drift and create painful merges.
  • MR template for infrastructure changes:

```markdown ## What and why ## Environments affected - [ ] dev - [ ] test - [ ] prod ## Plan summary

## Destroys / replacements

## Rollback ```

  • Conventional Commits (feat:, fix:, refactor:, chore(deps):) in module repos, so releases and changelogs are automated (shared modules).

Reading a plan

Plan: 3 to add, 1 to change, 1 to destroy.

Read from the bottom up:

  1. The summary line. Does "to destroy" match what you intended? Any non-zero destroy on an "add a tag" change is a stop sign.
  2. Every -/+ (replace) and the attribute marked # forces replacement. Replacements of stateful things (databases, storage accounts, Key Vaults, public IPs with DNS records) are outages or data loss.
  3. ~ updates in place: are the changed attributes the ones you touched?
  4. (known after apply) cascades: an unexpected unknown upstream often explains a surprising replacement downstream (frequently a depends_on on a data source; see dependencies).
  5. Moves and imports: has moved to and will be imported lines should match the moved/import blocks in the MR.
  6. Drift shown under "Objects have changed outside of Terraform": someone changed something; decide whether to revert or adopt before applying.

Machine help:

terraform show -json tfplan | jq -r '
  .resource_changes[]
  | select(.change.actions != ["no-op"])
  | "\(.change.actions | join(",")) \(.address)"'

GitLab's Terraform MR widget, Atlantis comments, or a small tool of your own can post this summary on the MR.

Code review checklist

Correctness

  • [ ] Plan matches the stated intent; no unexplained destroys/replacements
  • [ ] References instead of hard-coded names/IDs within the configuration
  • [ ] for_each over maps with stable keys, not count over lists
  • [ ] New resources have moved blocks if they replace renamed ones

Interface

  • [ ] Variables typed, described, validated where it matters
  • [ ] Outputs described; sensitive outputs marked (better: none)
  • [ ] No environment names in module logic

Security

  • [ ] No secrets in code, tfvars or outputs
  • [ ] Public access off by default; exceptions justified inline
  • [ ] Scanner suppressions have reasons
  • [ ] Role assignments scoped narrowly

Operations

  • [ ] Diagnostics/logging enabled
  • [ ] Tags applied (via a shared local.tags)
  • [ ] prevent_destroy / resource locks on stateful, hard-to-rebuild resources
  • [ ] Provider/module version changes are deliberate

Upgrades

Treat upgrades as routine maintenance, not projects:

What Cadence How
Terraform / OpenTofu minor Within a quarter of release Bump required_version and CI image in dev first; read the upgrade guide
Providers Weekly batch Renovate MR; init -upgrade; review plan for deprecations
Provider majors Planned Read the provider upgrade guide; migrate in the shared modules first
Shared modules Continuous Renovate + auto-merge for clean minor/patch plans
Scanners, pre-commit hooks Monthly pre-commit autoupdate / Renovate

Small, frequent upgrades are cheap. A two-year-old azurerm 3.x estate jumping to 4.x is a quarter of work; staying current is a few minutes a week.

Deprecation warnings in plans are free advance notice. Treat new ones as tickets.

Documentation

  • Module READMEs generated by terraform-docs, plus a runnable examples/ directory.
  • Root module READMEs: what the stack owns, who owns it, how to run it, its dependencies (which stacks must exist first), and its blast radius.
  • Architecture Decision Records for choices people will question later: "why separate subscriptions per environment", "why data sources instead of remote state", "why Terragrunt". One short Markdown file each, in the repo.
  • Runbooks for break-glass operations: unlocking state, restoring a state version, importing a hand-made emergency fix.

Team conventions worth writing down

  • Naming convention for resources and Terraform labels (hygiene)
  • Tagging standard (required keys, who sets them)
  • Which layer/stack owns which kinds of resources
  • When a new state is warranted
  • Required pre-commit hooks and CI gates
  • Supported Terraform/OpenTofu and provider version ranges
  • How emergencies are handled (portal change, then import or revert within N days)
in this section
* hcl development hygiene