terraform fmt: Usage, Options & Common CI Errors
Canonical formatting for your HCL, enforced automatically.
terraform fmt rewrites configuration files to a canonical format and style. As a CI check it keeps diffs clean and reviews focused on substance, not whitespace.
What it does
terraform fmt applies the standard Terraform style to .tf and .tfvars files - consistent indentation, aligned arguments, and ordered blocks. By default it edits files in place; with -check it only reports whether files are already formatted.
Common usage
# Format files in place
terraform fmt
# Format the whole tree, including nested modules
terraform fmt -recursive
# CI gate: fail if anything is unformatted, show the diff
terraform fmt -check -recursive -diffCommon error in CI: fmt -check fails the build
A formatting gate fails with a nonzero exit and a list of files that "would be formatted". The build stops but no fix is applied - -check never writes. Fix: run terraform fmt -recursive locally, commit the result, and push. To auto-fix in a pre-commit hook instead of failing CI, drop -check.
Key options
| Option | Purpose |
|---|---|
| -check | Exit nonzero if not formatted (no writes) |
| -recursive | Include subdirectories |
| -diff | Print the formatting diff |
| -write=false | Do not modify files |