Terraform (infrastructure as code)¶
Scope: managing infrastructure with Terraform or OpenTofu (tofu instead of terraform on the command line), from single projects to many teams sharing modules. For rules about AWS itself, see AWS; for pipelines that run Terraform, see GitHub Actions.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 10 Terraform style guide (HashiCorp): the baseline for code style, file layout, version pinning, repository structure, environments, secrets, testing and policy.
- 8 Module creation: recommended pattern (HashiCorp): how to scope modules by encapsulation, privileges and volatility. Read it with module composition and the standard module structure.
- 8 Best practices for using Terraform (Google Cloud): style, reusable and root modules, operations, security and testing. Much of it applies to other clouds too.
- 8 Manage sensitive data (HashiCorp): sensitive, ephemeral and write-only values, and how to secure state.
- 8 HCP Terraform workspace best practices (HashiCorp): how to split workspaces, each with one state file, by blast radius, volatility and team ownership.
- 7 Running Terraform in automation (HashiCorp): the plan, review and apply cycle in CI.
- 7 Best practices for using the Terraform AWS Provider (AWS Prescriptive Guidance): security, backends, code structure and provider versions on AWS.
- 7 OpenTofu language documentation (OpenTofu): the OpenTofu counterpart of the Terraform language docs, including features such as state and plan encryption.
Key rules¶
State and secrets¶
- 9
TF-1Store state in a remote backend with locking and encryption at rest, restrict who can read it, and never commit state files. State can contain passwords and keys, and concurrent runs can corrupt it. (HashiCorp, Remote state, HashiCorp, State locking, HashiCorp, Manage sensitive data, Google Cloud, Best practices for security) - 8
TF-2Give Terraform short-lived credentials, such as OIDC from the CI platform or HCP Terraform dynamic provider credentials, instead of static keys. Never put credentials in provider blocks or variables. (HashiCorp, Dynamic provider credentials, Terraform style guide, Google Cloud, Best practices for operations, HashiCorp, Running Terraform in automation) - 7
TF-3Keep secrets out of state where the provider allows it, with ephemeral values and write-only arguments (Terraform 1.10 and 1.11 or later), and protect saved plan files like state. With OpenTofu, you can also encrypt state and plan files. (HashiCorp, Manage sensitive data, Google Cloud, Best practices for security, HashiCorp, Running Terraform in automation, OpenTofu, State and plan encryption)
Structure and modules¶
- 8
TF-4Split infrastructure into separate root modules, each with its own state, by environment, blast radius, rate of change and team ownership. Keep stateful resources such as databases apart from stateless ones, and keep each state small (Google suggests at most 100 resources). (HashiCorp, Workspace best practices, Google Cloud, Best practices for root modules) - 7
TF-5Give each environment its own directory, with its own backend, that calls shared modules. Don't use CLI workspaces for environments that need separate credentials or access controls. (Terraform style guide, HashiCorp, Manage workspaces, Google Cloud, Best practices for root modules) - 7
TF-6Rename and move resources withmovedblocks, and keep oldmovedblocks in shared modules. Otherwise Terraform destroys the resource and creates a new one. (HashiCorp, Refactor modules) - 6
TF-7Keep the module tree flat: compose child modules in the root module and pass their dependencies in as variables. (HashiCorp, Module composition) - 6
TF-8Write modules that do one thing well at a higher level of abstraction, not thin wrappers around a single resource. (HashiCorp, Module creation: recommended pattern, HashiCorp, Creating modules) - 5
TF-9Protect costly stateful resources, such as databases and storage, withprevent_destroy, sparingly. It doesn't stop destruction when the resource block is removed. (HashiCorp, lifecycle meta-argument)
Versions and delivery¶
- 8
TF-10Pin versions: setrequired_version, constrain providers with~>in root modules but only by minimum in reusable modules, pin module versions, and commit.terraform.lock.hcl. Review the pins regularly, for example with Dependabot. (HashiCorp, Version constraints: best practices, HashiCorp, Dependency lock file, Google Cloud, Best practices for operations) - 8
TF-11Run Terraform from a pipeline: plan every change, save the plan with-out, and apply exactly that plan after review. (HashiCorp, Running Terraform in automation, Google Cloud, Best practices for operations) - 6
TF-12Runterraform fmt -check,terraform validateand TFLint on every change, and test reusable modules withterraform test. (Terraform style guide, HashiCorp, Tests) - 6
TF-13Check plans against security and organisation policies as code before applying them. (Terraform style guide, HashiCorp, Policy enforcement overview) - 5
TF-14Detect drift on a schedule, for example withterraform plan -detailed-exitcodeor HCP Terraform health assessments. (HashiCorp, terraform plan, HashiCorp, Health assessments)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7
terraform fmt -check,terraform validateandterraform test: the built-in checks.fmt -checkexits non-zero when files aren't formatted,validatechecks that the configuration is syntactically valid and internally consistent, andtestruns the module's test files. ChecksTF-12. - 6 TFLint Terraform ruleset: its recommended rules require
required_version, provider version constraints, versions for registry modules and pinned Git module sources. It doesn't check~>bounds or the lock file. Partly checksTF-10. - 6 Checkov Terraform policies: misconfiguration checks on HCL or plan JSON, including module sources without a pinned hash or version tag (
CKV_TF_1,CKV_TF_2) and hard-coded AWS keys in the provider (CKV_AWS_41). ChecksTF-13, and partlyTF-2andTF-10. - 6 HCP Terraform policy enforcement: evaluates Sentinel, OPA or Terraform policies on every run, and health assessments detect drift on a schedule. Checks
TF-13andTF-14. - 5 Trivy Terraform scanning: an alternative to Checkov that scans HCL and plans for misconfigurations and secrets. Partly checks
TF-2andTF-13. - 5 Dependabot for Terraform: opens pull requests for new provider and module versions. Partly checks
TF-10.
Tutorials and further reading¶
- 7 Terraform tutorials (HashiCorp): official hands-on tutorials, from getting started to modules, state, policy and automation.
- 6 Terraform: Up & Running (Yevgeniy Brikman, book): state, modules, testing and team workflows in depth.
- 5 Terraform Best Practices (Anton Babenko): a free community guide to code structure and naming.