terraform fmt: Format Terraform Code and Fail the Build When It Is Not Formatted (-check, -diff, -recursive, Exit Code 3, pre-commit, GitHub Actions)

· Rahul Wagh · Nov. 30, 2026, 10:15 a.m.
Summary
This blog post discusses how to use the `terraform fmt` command to enforce consistent formatting for Terraform code and automatically fail builds if the code isn't formatted properly. It details the benefits of using `-check`, `-diff`, and `-recursive` flags for CI, along with tips for setting up pre-commit hooks to ensure code is formatted before committing. The author shares common pitfalls related to command usage.