0
0
Terraformcloud~3 mins

Terraform fmt for formatting - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you write Terraform code, it can get messy and hard to read. Terraform fmt helps by automatically fixing the layout and spacing so your code looks neat and consistent.
When you want to make your Terraform files easier to read for yourself and others.
Before sharing your Terraform code with teammates to keep a consistent style.
After editing Terraform files manually to fix any formatting issues.
When you want to avoid formatting mistakes that can cause confusion or errors.
Before committing Terraform code to version control to keep the repository clean.
Commands
This command formats all Terraform files in the current directory to follow the standard style.
Terminal
terraform fmt
Expected OutputExpected
No output (command runs silently)
This checks if any Terraform files need formatting without changing them. It helps you see if your code is already formatted correctly.
Terminal
terraform fmt -check
Expected OutputExpected
No output (command runs silently)
-check - Checks formatting without making changes
This formats Terraform files in the current directory and all subdirectories recursively.
Terminal
terraform fmt -recursive
Expected OutputExpected
No output (command runs silently)
-recursive - Formats files in all subfolders
Key Concept

If you remember nothing else from this pattern, remember: terraform fmt keeps your code clean and consistent automatically.

Common Mistakes
Not running terraform fmt before committing code
This causes inconsistent formatting that makes code harder to read and review.
Always run terraform fmt to format your files before committing.
Using terraform fmt without the -recursive flag in projects with subfolders
Only files in the current folder get formatted, leaving others messy.
Use terraform fmt -recursive to format all files in the project.
Ignoring terraform fmt -check output
You might miss that files need formatting and commit unformatted code.
Use terraform fmt -check in CI or before commits to catch unformatted files.
Summary
terraform fmt formats Terraform files to a standard style automatically.
Use terraform fmt -recursive to format files in all subdirectories.
Use terraform fmt -check to verify if files need formatting without changing them.