Skip to content
Latchkey

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

Terminal
# 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 -diff

Common 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

OptionPurpose
-checkExit nonzero if not formatted (no writes)
-recursiveInclude subdirectories
-diffPrint the formatting diff
-write=falseDo not modify files

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →