Enforce Consistent Terraform Code with fmt and validate
terraform fmt and validate catch style and syntax issues before they reach code review or production.
What
terraform fmt automatically formats your HCL files to a canonical style, standardizing indentation, alignment, and spacing. terraform validate checks your configuration for syntax errors, invalid references, and internal consistency. Together they form the first line of defense for code quality.
Why It Matters
Inconsistent formatting makes code reviews painful and diffs noisy. Syntax errors caught during apply waste time and can leave infrastructure in a partial state. Running both commands in CI/CD ensures every change meets baseline quality standards before anyone reviews it.
Example
# Format all .tf files in the current directory
terraform fmt
# Recursively format all files in subdirectories
terraform fmt -recursive
# Check formatting without modifying files (great for CI)
terraform fmt -check
# Exit code 0 = formatted, exit code 3 = needs formatting
# Show which files would be changed
terraform fmt -diff
# Validate configuration syntax and consistency
terraform init # Required before validate
terraform validate
# Example CI/CD pipeline step (GitHub Actions)
# - name: Terraform Format Check
# run: terraform fmt -check -recursive
# - name: Terraform Validate
# run: terraform validateCommon Mistake
Only running terraform validate but not terraform fmt. Your code might be syntactically valid but inconsistently formatted, making code reviews harder and git diffs noisy with whitespace changes.
Quick Fix
Add both terraform fmt -check -recursive and terraform validate to your CI/CD pipeline. Use terraform fmt -check (not terraform fmt) in CI so it fails on unformatted code instead of silently fixing it. Developers run terraform fmt locally before committing.
Key Takeaways
- 1terraform fmt = consistent code formatting
- 2terraform fmt -check = CI-friendly format check
- 3terraform validate = syntax and reference checking
- 4Run both in CI/CD for every pull request
- 5fmt -recursive formats all subdirectories
Was this tip helpful?
Help us improve the DevOpsPath daily collection