FilePurposeterraform.tfTerraform + provider version requirementsproviders.tfProvider configurationsmain.tfPrimary resources and data sourcesvariables.tfInput variables (alphabetical)outputs.tfOutput values (alphabetical)locals.tfLocal values
web_api, not webAPI or web-apiaws_instance.web_api not aws_instance.web_api_instancethis for singleton resources (one of that type per module)vpc_cidr_block not cidrResources: count/ for_each (blank line after) → arguments → nested blocks → tags → depends_on → lifecycle (last)
Variables: description → type → default → validation → nullable
Every variable needs type + description. Every output needs description. Mark secrets sensitive = true.
TypeScopeExampleResource ModuleSingle logical groupVPC + subnets, SG + rulesInfrastructure ModuleCollection of resource modulesNetworking + compute for one regionCompositionComplete infrastructureSpans regions/accountstext
module-name/
├── main.tf, variables.tf, outputs.tf, versions.tf
├── examples/
│ ├── minimal/
│ └── complete/
└── tests/
└── defaults.tftest.hcl
Keep modules small (single responsibility). examples/ double as documentation and integration test fixtures. Semantic versioning for all published modules.
ScenarioUseBoolean toggle (create or skip)count = condition ? 1 : 0Named/keyed items that may reorderfor_each = toset(list) or mapFixed identical replicascount = N
Default to for_each: removing a middle item from a count list recreates all subsequent resources. Use count only for boolean conditionals or truly identical replicas.
ComponentStrategyExampleTerraformPin minorrequired_version = "~> 1.9.0"ProvidersPin majorversion = "~> 5.0"Modules (prod)Pin exactversion = "5.1.2"Modules (dev)Allow patchversion = "~> 5.1.0"
Key modern features: moved blocks (1.1+), optional() with defaults (1.3+), native testing (1.6+), mock providers (1.7+), cross-variable validation (1.9+), write-only arguments (1.11+).
Stacks (HCP; check current release status): orchestrates multiple configs as a single deployment unit. Evaluate for multi-environment patterns.
use_lockfile = true (1.10+), Azure Blob, GCS, or Terraform Cloud. Never local state for shared infrastructure. DynamoDB-based S3 locking ( dynamodb_table) is deprecated and slated for removal; prefer use_lockfile. Both may be set at once while migrating an existing table off.terraform { encryption { key_provider "pbkdf2" "k" {...} method "aes_gcm" "m" { keys = key_provider.pbkdf2.k } state { method = method.aes_gcm.m } plan { method = method.aes_gcm.m } } } encrypts state and plan files client-side (or via TF_ENCRYPTION). Roll out with a fallback { method = method.unencrypted.x } so existing plaintext state still loads, and never rename a key provider or method without a fallback block. OpenTofu also accepts var.*/ local.* in backend {} arguments and in module source/ version (resolved at init; no state or provider-function references); the same HCL is a hard error in Terraform ("A backend block cannot refer to named values")..tfstate, .terraform/, or *.tfplan. Always commit .terraform.lock.hcl.default_tags on provider for consistent resource tagging.0.0.0.0/0 ingress without explicit justification.terraform fmt -recursive rewrites files), then verify ( terraform validate && tflint && trivy config .)moved blocks with from and to addresses for refactoring resource names/modules without destroy-recreate. Retain historical moves for downstream upgrades; remove only after every affected state has migrated, or as an explicitly breaking module release.lifecycle { ignore_changes = [attr] } suppresses updates only, and it substitutes the prior state value at plan time, on the first plan after the config change, with no "first apply" exception. Two consequences reviewers get backwards: (1) on an already-provisioned resource the literal in the config is never written, and ForceNew never fires because ignore_changes erased the diff before replacement is evaluated, so a change that replaces a committed value with a placeholder scrubs the repository and leaves the remote value live; (2) ignore_changes does not apply on create, so any later -replace, taint, state rm + re-add, or manual deletion re-seeds the placeholder over a value that was set out of band. Keep only the container resource in configuration and provision the value entirely out of band, or state the restore step in the runbook for every replace path.terraform force-unlock <ID>, only after confirming no other operation runningterraform plan -refresh-only to detect, terraform apply -refresh-only to acceptterraform apply -replace=ADDR (not deprecated terraform taint)import blocks (1.5+) for declarative import, or terraform import ADDR IDUse locals with try() to control deletion ordering without explicit depends_on:
hcl
locals {
vpc_id = try(aws_vpc_ipv4_cidr_block_association.this[0].vpc_id, aws_vpc.this.id, "")
}
This forces Terraform to destroy subnets before CIDR associations, which prevents deletion errors.
cidrsubnet(var.vpc_cidr, 8, count.index) for calculated subnet CIDRs; never hardcode subnetsprovider "aws" { alias = "eu_west_1" } + providers = { aws = aws.eu_west_1 } in module blocksRun before declaring done:
bash
terraform fmt -check && terraform validate && tflint && trivy config .
All commands must pass with zero errors. Inspect providers, data sources, provisioners, and external commands before selecting test files. Include safe plan tests and fully mocked apply tests in completion checks. Keep real-service or infrastructure tests behind the task's authorization and cost boundary. Pass the root-relative test filename, such as terraform test -filter=tests/vpc_unit_test.tftest.hcl, and verify that the intended file completed at least one run; an exit code alone can accept an unknown filter with no tests selected. Use the checked selection recipe in native-test-patterns.md.
Read the relevant reference before implementing or reviewing the matching behavior: