Terraform Format

Readability is crucial when working with infrastructure as code. Terraform configurations can quickly become complex, making consistent formatting an essential practice. The terraform fmt command ensures your code adheres to the standard HCL (HashiCorp Configuration Language) style, improving readability and reducing errors.

Why Use terraform fmt?

  • Automatically formats configuration files.
  • Enforces Terraform's canonical style.
  • Makes collaborative work easier by maintaining consistent formatting.

How to Use It?

  • To format files in the current directory: Run terraform fmt. This will scan all .tf files in the directory and apply the standard formatting.
  • To include subdirectories: Run terraform fmt --recursive. This ensures that files in all nested directories are formatted.
  • To preview changes without applying them: Use the --diff flag, e.g., terraform fmt --diff, to see the differences between the original and formatted files.
  • To check formatting in CI/CD pipelines: Use terraform fmt --check. This command verifies if the files are already formatted correctly and returns an error if they're not.

Example: Formatting Terraform Code

Let’s say you have a main.tf file with inconsistent formatting, like this:

resource "aws_instance" "example" {
ami           = "ami-123456"
instance_type= "t2.micro"
  tags = {
 Name = "example-instance"
}
}

Run the command terraform fmt. After formatting, the file will look like this:

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
  tags = {
    Name = "example-instance"
  }
}

Use Case

Imagine you’re working with a team, and each member writes Terraform code in their preferred style. Over time, inconsistencies can lead to errors and confusion. By running terraform fmt, you ensure all configuration files are uniformly formatted, reducing friction during code reviews and debugging.

Conclusion

The terraform fmt command is an easy yet powerful way to maintain clean, consistent, and readable Terraform configurations. Make it a habit to run this command before every commit to ensure your codebase is always in tip-top shape.