पाठ 23 / 25

fmt and validate

Fast checks before plan.

Style and correctness

terraform fmt rewrites files to the canonical style; fmt -check -diff reports differences without changing files (exit code 3 when changes are needed), ideal for CI. terraform validate checks syntax, references and argument names against provider schemas, catching typos like contents instead of content without touching real infrastructure. Linters such as TFLint and security scanners such as Checkov or Trivy add provider-specific and security rules.

Consistent, checked, reviewed

Formatting, validation and plan-based reviews keep Terraform changes safe as teams grow.

Three ideas: fmt and validate, CI workflow, checklist.
Figure 8.1 — Quality checks, CI and checklist.

fmt -check on a messy file, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. fmt shows the diff it would apply (indentation and aligned equals signs) and exits with code 3, which fails a CI check.

terraform fmt -check -diff -no-color main.tf | tail -6; echo "exit code: ${PIPESTATUS[0]}"

Output:

 variable "region" {
-type = string
-  default    =   "ap-south-1"
+  type    = string
+  default = "ap-south-1"
 }
exit code: 3

validate catching a typo, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. validate reports that the argument "contents" is not expected and suggests "content".

terraform validate -no-color 2>&1 | grep -E "Error|contents|not expected"

Output:

Error: Unsupported argument
  11:   contents = "hello"
An argument named "contents" is not expected here. Did you mean "content"?

त्वरित जाँच: What does terraform validate check?

  • Syntax, references and arguments against provider schemas, without calling cloud APIs
  • Whether resources exist in the cloud
  • Costs
  • Who wrote the code
Answer

Syntax, references and arguments against provider schemas, without calling cloud APIs — Cheap correctness checks.