0
0
TerraformHow-ToBeginner · 3 min read

How to Use terraform fmt: Format Terraform Configuration Files

Use terraform fmt to automatically format your Terraform configuration files to a standard style. Run terraform fmt in your project directory to format all files, or specify a path to format specific files.
📐

Syntax

The basic syntax of terraform fmt is simple and easy to use. You can run it without arguments to format all Terraform files in the current directory. You can also specify a path to format files in a specific folder or file.

  • terraform fmt: Formats all Terraform files in the current directory.
  • terraform fmt [options] [path]: Formats files at the given path.
  • -recursive: Option to format files in all subdirectories recursively.
bash
terraform fmt [options] [path]

# Example:
terraform fmt
terraform fmt -recursive ./modules
💻

Example

This example shows how to use terraform fmt to format Terraform files in the current directory and recursively in subdirectories.

bash
# Unformatted Terraform file example (main.tf):
resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

# Run terraform fmt to fix formatting:
terraform fmt

# To format all files recursively:
terraform fmt -recursive .
Output
main.tf modules/network/main.tf modules/compute/main.tf
⚠️

Common Pitfalls

Common mistakes when using terraform fmt include:

  • Running terraform fmt outside the Terraform project directory, which results in no files being formatted.
  • Not using the -recursive flag when you want to format files in subfolders.
  • Expecting terraform fmt to fix syntax errors or validate configuration; it only formats code style.

Always check you are in the correct directory and use -recursive if needed.

bash
## Wrong usage (no recursive flag):
terraform fmt ./modules

## Correct usage (with recursive flag):
terraform fmt -recursive ./modules
📊

Quick Reference

CommandDescription
terraform fmtFormat all Terraform files in current directory
terraform fmt -recursive .Format all Terraform files in current directory and subdirectories
terraform fmt path/to/file.tfFormat a specific Terraform file
terraform fmt -helpShow help and options for terraform fmt

Key Takeaways

Run terraform fmt in your Terraform project directory to format files automatically.
Use the -recursive flag to format files in all subdirectories.
terraform fmt only changes formatting, not syntax or validation.
Always run terraform fmt before committing code for consistent style.
You can specify a file or folder path to format specific files.