Andrew Mercer
on this page

Hygiene is the set of habits that don't change what Terraform does but change how quickly a human can understand it. Most of it can be automated, and what can be automated should be: humans shouldn't spend review time on formatting.

Formatting

terraform fmt -recursive          # rewrite in place
terraform fmt -check -recursive   # CI: fail if anything would change
terraform fmt -diff               # show what would change

terraform fmt aligns = signs within a block, normalises indentation (two spaces), and fixes spacing. It's not configurable, which is the point. Run it on save in your editor (terraform-ls / the HashiCorp extension), in pre-commit, and in CI.

Terragrunt files: terragrunt hcl fmt. Test files and .tfquery.hcl files are formatted by terraform fmt too (.tfquery.hcl since 1.15).

File layout

Standard files for a module or root module:

File Contents
main.tf Resources and module calls. Split by concern when it grows (network.tf, identity.tf, monitoring.tf)
variables.tf All variable blocks
outputs.tf All output blocks
locals.tf Locals used across files (locals used in one file can live in that file)
versions.tf terraform { required_version, required_providers }
providers.tf Root modules only. provider blocks
backend.tf Root modules only. backend / cloud block
data.tf Data sources, if there are many
imports.tf / moved.tf Refactoring blocks, so they're easy to find and later remove
terraform.tfvars / env/*.tfvars Root modules only
README.md Generated by terraform-docs
tests/*.tftest.hcl Tests
examples/*/ Runnable examples (modules)

Within a file, order blocks so the file reads top-down: data sources and locals that feed resources near the top, then resources in dependency order.

Naming

Terraform labels

Labels are for humans reading the configuration. Cloud names are for the cloud. Keep them separate.

  • snake_case, always: azurerm_subnet.private_endpoints, not azurerm_subnet.private-endpoints. Hyphens are legal but read as subtraction in expressions.
  • Don't repeat the type: azurerm_storage_account.logs, not azurerm_storage_account.logs_storage_account.
  • Use this for the single, primary resource of its type in a module: azurerm_key_vault.this.
  • Don't encode environment or region in labels. azurerm_resource_group.rg-project-eus-dev repeats information that belongs in the name argument and the directory. It's how label/name mismatches like eus vs weu happen (naming validation). Prefer azurerm_resource_group.app and derive the name.
  • Plural for collections: azurerm_subnet.this with for_each is fine; so is azurerm_subnet.app_subnets. Be consistent.
  • Variables and outputs: snake_case, positive booleans (enable_x, x_enabled, never disable_x), units in names (retention_days, timeout_seconds).

Cloud resource names

Build them once, from parts, in locals:

locals {
  # Azure CAF-style: <type>-<workload>-<env>-<region>-<instance>
  name = {
    rg      = "rg-${var.workload}-${var.env}-${var.location_short}"
    vnet    = "vnet-${var.workload}-${var.env}-${var.location_short}"
    kv      = substr("kv-${var.workload}-${var.env}-${var.location_short}", 0, 24)
    storage = substr(replace("st${var.workload}${var.env}${var.location_short}", "-", ""), 0, 24)
  }
}

Or use a naming module (Azure's Azure/naming/azurerm) so the convention lives in one place. Validate names against the provider's length/character rules in tests (testing).

Argument order within a block

Consistency helps scanning. A common convention:

  1. Meta-arguments: count / for_each, provider
  2. Identity: name, resource_group_name, location
  3. Other arguments, required before optional
  4. Nested blocks
  5. tags
  6. depends_on
  7. lifecycle
resource "azurerm_linux_web_app" "this" {
  for_each = var.apps

  name                = "app-${each.key}-${var.env}-${var.location_short}"
  resource_group_name = var.resource_group_name
  location            = var.location
  service_plan_id     = azurerm_service_plan.this.id
  https_only          = true

  site_config {
    minimum_tls_version = "1.2"
  }

  identity {
    type = "SystemAssigned"
  }

  tags = local.tags

  lifecycle {
    ignore_changes = [app_settings["WEBSITE_RUN_FROM_PACKAGE"]]
  }
}

Types and interfaces

  • Every variable has type and description. TFLint can enforce both.
  • Precise types: map(object({...})) with optional(), not any (types).
  • nullable = false on variables that must never be null.
  • Validate formats and ranges at the boundary.
  • Secure defaults; risky options are explicit opt-ins.

Avoid hard-coding

Hard-coded Instead
Subscription / tenant / account IDs Variables, provider env vars, data "azurerm_client_config"
Resource IDs from other stacks Data sources by name, or remote state
Names of resources in the same config References (azurerm_x.y.name), which also create dependencies
Region strings scattered everywhere var.location once
IP ranges Variables, cidrsubnet() from a single parent range
Magic numbers Named locals with a comment

Comments

  • Comment why, not what. # Purge protection can't be disabled once enabled; dev keeps it off so vaults can be recreated is useful. # Create key vault isn't.
  • Every depends_on, ignore_changes, scanner suppression, -target in a script and nonsensitive() gets a comment explaining it.
  • Link to issues for provider-bug workarounds so they can be removed later: # Workaround for hashicorp/terraform-provider-azurerm#16326; remove when fixed.
  • Use # (what terraform fmt and most linters expect), not //.

Locals discipline

  • Locals for derived values and normalised input, not for constants that should be variables.
  • Avoid long chains of locals across files. If understanding local.x needs four jumps, inline something.
  • Name boolean locals as questions: local.needs_private_endpoint.

Expression style

  • Prefer for_each over count for collections (loops).
  • One ternary per expression; use lookup maps for more branches (conditionals).
  • one(x[*].attr) for conditional resources rather than length(x) > 0 ? x[0].attr : null.
  • jsonencode() / yamlencode() rather than heredoc JSON/YAML.
  • templatefile() with .tftpl files for anything longer than a few lines.
  • "${var.x}" → var.x. Interpolation-only strings are a 0.11 leftover.
  • try() only where errors are expected (decoded data); explicit guards elsewhere.

Linting with TFLint

terraform validate checks syntax and types. TFLint checks conventions and provider semantics: invalid VM sizes, deprecated arguments, unused variables, missing types.

# .tflint.hcl
config {
  call_module_type = "local"
  force            = false
}

plugin "terraform" {
  enabled = true
  preset  = "recommended"
}

plugin "azurerm" {
  enabled = true
  version = "0.28.0"
  source  = "github.com/terraform-linters/tflint-ruleset-azurerm"
}

rule "terraform_naming_convention" {
  enabled = true
  format  = "snake_case"
}

rule "terraform_documented_variables" { enabled = true }
rule "terraform_documented_outputs"   { enabled = true }
rule "terraform_typed_variables"      { enabled = true }
rule "terraform_unused_declarations"  { enabled = true }
rule "terraform_standard_module_structure" { enabled = true }
rule "terraform_required_version"     { enabled = true }
rule "terraform_required_providers"   { enabled = true }
tflint --init
tflint --recursive --format compact

Inline ignore with a reason: # tflint-ignore: terraform_unused_declarations # kept for backwards compatibility until v4.

Documentation with terraform-docs

# .terraform-docs.yml
formatter: markdown table
output:
  file: README.md
  mode: inject
settings:
  anchor: true
  default: true
  required: true
  sensitive: true
  type: true
sort:
  enabled: true
  by: required

Put <!-- BEGIN_TF_DOCS --> and <!-- END_TF_DOCS --> in the README. Everything outside the markers (purpose, examples, upgrade notes) stays hand-written.

Pre-commit

One config per repo, the same in CI:

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.96.1
    hooks:
      - id: terraform_fmt
      - id: terraform_validate
      - id: terraform_tflint
      - id: terraform_docs
        args: ["--args=--config=.terraform-docs.yml"]
      - id: terraform_trivy
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-merge-conflict
      - id: detect-private-key
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks

Security-specific hooks are in scanning tools.

.gitignore

# Terraform
.terraform/
*.tfstate
*.tfstate.*
crash.log
crash.*.log
*.tfplan
tfplan*
override.tf
override.tf.json
*_override.tf
*_override.tf.json
.terraformrc
terraform.rc

# Terragrunt
.terragrunt-cache/
.terragrunt-stack/

# Local environment
.envrc
# Only if you use *.auto.tfvars for local-only overrides
# (gitignore has no trailing comments, so notes go on their own line)
*.auto.tfvars

# Commit this one:
!.terraform.lock.hcl

If your repo intentionally commits *_override.tf (Terragrunt-generated files are not committed; they live in the cache), adjust accordingly.

Editor setup

  • terraform-ls (HashiCorp's language server): completion, go-to-definition, validation. VS Code extension, or Neovim via nvim-lspconfig, or Helix/Zed built-ins.
  • tofu-ls for OpenTofu-specific syntax.
  • Format on save with terraform fmt.
  • .editorconfig with two-space indentation for *.tf, *.hcl, *.tftest.hcl.

Hygiene checklist

  • [ ] terraform fmt -check passes
  • [ ] TFLint clean (with provider ruleset)
  • [ ] Every variable and output typed and described
  • [ ] snake_case labels; no env/region in labels
  • [ ] No hard-coded IDs; references within the configuration
  • [ ] Comments on every depends_on, ignore_changes, suppression
  • [ ] README generated and current
  • [ ] Lock file committed; .terraform/ and state ignored
  • [ ] Pre-commit installed and mirrored in CI