Terraform Best Practices

Chapter 1 · Practice 1 of 4

Use the standard file layout for every root module

From Structure and style

Why it matters

When every configuration splits its blocks the same way, people find things without searching. The Terraform style guide recommends:

FileHolds
terraform.tfOne terraform block with required_version and required_providers
providers.tfAll provider blocks
backend.tfThe backend configuration
main.tfResources and data sources
variables.tfVariables, in alphabetical order
outputs.tfOutputs, in alphabetical order
locals.tfLocals used across files

As a configuration grows, split main.tf by logical group such as network.tf, storage.tf and compute.tf rather than letting one file reach thousands of lines.

Do

  • Keep exactly one terraform block, in terraform.tf
  • Split large main.tf files by area: network, storage, compute

Avoid

  • Scattering provider blocks across several files