Terraform’s terraform fmt command enforces the canonical style for configuration files. The tool is intentionally opinionated and non-configurable, guaranteeing a uniform format across codebases so reviewers can focus on substance rather than style. Integrate it with to validate and format code automatically before it reaches version control.
For example:
In CI pipelines, use terraform fmt -check to verify compliance. It exits with status 0 when all files are correctly formatted; otherwise, it returns a non-zero code and lists the offending files. Centralizing formatting in this way removes merge friction and enforces a consistent standard across teams.
Use .editorconfig: helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs. Include an .editorconfig file in your repositories to maintain consistent whitespace and indentation.
Example .editorconfig:
is a framework for managing and maintaining multi-language pre-commit hooks. It is written in Python and is a powerful tool to do something automatically on a developer's machine before code is committed to a git repository. Normally, it is used to run linters and format code (see ).
With Terraform configurations pre-commit can be used to format and validate code, as well as to update documentation.
Check out the to familiarize yourself with it, and existing repositories (eg, ) where this is used already.
is a tool that does the generation of documentation from Terraform modules in various output formats. You can run it manually (without pre-commit hooks), or use to get the documentation updated automatically.
Use # for comments. Avoid // or block comments.
Example:
Section Headers: Delimit section headers in code with # ----- or ###### for clarity.
Example:
@todo: Document module versions, release, GH actions
Blog post by :
# .pre-commit-config.yaml
repos:
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.99.4
hooks:
- id: terraform_fmt[*]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
[*.{tf,tfvars}]
indent_style = space
indent_size = 2
[Makefile]
indent_style = tab# This is a comment explaining the resource
resource "aws_instance" "this" {
# ...
}# --------------------------------------------------
# AWS EC2 Instance Configuration
# --------------------------------------------------
resource "aws_instance" "this" {
# ...
}