fmt and validate

terraform fmt formats code to the canonical style and terraform validate checks it for errors.

Syntaxterraform fmt terraform validate

Two quick commands keep your configuration clean and correct.

terraform fmt

Rewrites your files to the canonical HCL style — consistent indentation, aligned equals signs, # comments. Run it before every commit.

terraform validate

Checks that your configuration is internally consistent: valid syntax, correct argument names, right types. It does not talk to any cloud, so it is fast and safe to run anywhere.

Example

Example · bash
# Format all files in place, recursively
terraform fmt -recursive

# Check formatting without changing files (for CI)
terraform fmt -check

# Validate configuration syntax and types
terraform validate

When to use it

  • A pre-commit hook runs terraform fmt --check so any push with non-canonical formatting is rejected before it reaches the remote branch.
  • A CI pipeline runs terraform validate after init to catch reference errors and missing required arguments before spending time on a full plan.
  • An engineer runs terraform fmt -recursive on a large repository to normalize all .tf files to canonical indentation in one command.

More examples

Format all files recursively

Runs fmt to auto-fix formatting and shows the -check flag that makes CI fail without modifying files.

Example · bash
# Rewrite all .tf files to canonical style
terraform fmt -recursive

# Check formatting without rewriting (CI mode)
terraform fmt -check -recursive
# Returns exit code 1 if any file needs formatting

Validate configuration correctness

Runs validate after init to catch HCL errors and broken references before running a plan against real cloud APIs.

Example · bash
terraform init -backend=false  # skip backend for validate
terraform validate
# Success! The configuration is valid.

# On error:
# Error: Reference to undeclared resource
#   resource "aws_instance" "app" references
#   aws_subnet.private which does not exist

Pre-commit hook for fmt and validate

A pre-commit hook that blocks commits with formatting issues or validation errors, enforcing quality at the developer's machine.

Example · bash
#!/bin/bash
# .git/hooks/pre-commit

set -e

echo "Running terraform fmt check..."
terraform fmt -check -recursive

echo "Running terraform validate..."
terraform validate

echo "Pre-commit checks passed."

Discussion

  • Be the first to comment on this lesson.