terraform fmt Command Reference
Canonical formatting for your HCL, enforced automatically.
terraform fmt rewrites configuration files to a canonical 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. By default it edits files in place; with -check it only reports whether files are already formatted and exits nonzero if not.
Common flags and usage
- -check: exit nonzero if files are not formatted (no writes)
- -recursive: include subdirectories and nested modules
- -diff: print the formatting diff
- -write=false: do not modify files
Example
shell
- name: Format check
run: terraform fmt -check -recursive -diffIn CI
Use terraform fmt -check -recursive as a non-mutating gate. If it fails, run terraform fmt -recursive locally, commit, and push. Drop -check in a pre-commit hook to auto-fix instead of failing the build.
Key takeaways
- fmt rewrites HCL to a canonical style; -check only reports without writing.
- Add -recursive to cover nested modules in one pass.
- Use -check in CI as a gate; run plain fmt locally to fix violations.
Related guides
terraform validate Command ReferenceReference for terraform validate in CI/CD: a fast, offline configuration check that runs after init and gates…
terraform init Command ReferenceReference for terraform init in CI/CD: initialize providers, modules, and the backend, pass backend-config, a…
terraform plan Command ReferenceReference for terraform plan in CI/CD: preview changes, save a plan file with -out for a later apply, and gat…