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, notazurerm_subnet.private-endpoints. Hyphens are legal but read as subtraction in expressions.- Don't repeat the type:
azurerm_storage_account.logs, notazurerm_storage_account.logs_storage_account. - Use
thisfor 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-devrepeats information that belongs in thenameargument and the directory. It's how label/name mismatches likeeusvsweuhappen (naming validation). Preferazurerm_resource_group.appand derive the name. - Plural for collections:
azurerm_subnet.thiswithfor_eachis fine; so isazurerm_subnet.app_subnets. Be consistent. - Variables and outputs:
snake_case, positive booleans (enable_x,x_enabled, neverdisable_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:
- Meta-arguments:
count/for_each,provider - Identity:
name,resource_group_name,location - Other arguments, required before optional
- Nested blocks
tagsdepends_onlifecycle
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
typeanddescription. TFLint can enforce both. - Precise types:
map(object({...}))withoptional(), notany(types). nullable = falseon 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 recreatedis useful.# Create key vaultisn't. - Every
depends_on,ignore_changes, scanner suppression,-targetin a script andnonsensitive()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
#(whatterraform fmtand 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.xneeds four jumps, inline something. - Name boolean locals as questions:
local.needs_private_endpoint.
Expression style¶
- Prefer
for_eachovercountfor collections (loops). - One ternary per expression; use lookup maps for more branches (conditionals).
one(x[*].attr)for conditional resources rather thanlength(x) > 0 ? x[0].attr : null.jsonencode()/yamlencode()rather than heredoc JSON/YAML.templatefile()with.tftplfiles 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. .editorconfigwith two-space indentation for*.tf,*.hcl,*.tftest.hcl.
Hygiene checklist¶
- [ ]
terraform fmt -checkpasses - [ ] TFLint clean (with provider ruleset)
- [ ] Every variable and output typed and described
- [ ]
snake_caselabels; 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