terraform fmt: Format Terraform Code and Fail the Build When It Is Not Formatted (-check, -diff, -recursive, Exit Code 3, pre-commit, GitHub Actions)
TL;DR
terraform fmtrewrites.tf,.tfvarsand.tftest.hclfiles in place to the canonical style (two-space indentation, aligned=) and prints the names of the files it changed. It does not touch.tf.json.terraform fmt -check -diff -recursiveis the CI form. It writes nothing, prints each unformatted file with a unified diff, and on Terraform 1.17.2 it exited with code 3 when files needed changes and 0 when everything was clean.-recursivematters: without it only the current directory is scanned, so a module inmodules/net/is silently skipped.- Block the commit, not the pull request: a local pre-commit hook running
terraform fmt -check -difffailed my commit with the diff on screen and let it through afterterraform fmt. - One trap:
-no-colormust be written with a single dash afterfmt;--no-colorand a global-no-colorbefore the subcommand are both rejected. - Not your exact case? If the error is about the configuration itself and not its style, start with the Terraform index; to see a module that benefits from this, read terraform template.
Table of Content
- What terraform fmt changes and what it leaves alone
- Check mode, diff and the exit code
- Which files fmt touches
- Recursive, stdin and a syntax error
- A pre-commit hook that blocks unformatted code
- The same check in GitHub Actions
- What broke when I ran this
- Options table
I run terraform fmt on every module before I commit, mostly because I got tired of review comments about indentation. The command is small, but the difference between the write mode and the check mode, and the exit code, decides whether it is a convenience or a real gate. All output below is from Terraform 1.17.2 on 2026-11-30. The binary came from the official release archive and I checked it against the published SHA256SUMS file.
What terraform fmt changes and what it leaves alone
I made a small project with a root main.tf and a module file modules/net/vpc.tf, both badly indented. The terraform fmt reference says the command scans the current directory unless you give it a target (a directory, a file, or - for standard input). It fixes whitespace only: indentation, the alignment of = signs inside a block, and spacing around =. It never renames, reorders or removes arguments. HashiCorp's style conventions describe the rules fmt applies.
Check mode, diff and the exit code
Plain terraform fmt -check prints the file names and exits non-zero; the docs only promise "non-zero". In practice I saw exactly 3:
1$ terraform fmt -check
2main.tf
3$ echo $?
43
Adding -diff and -recursive gives the output I want in a pull request log. Both files are listed, each with a unified diff, and nothing was written to disk:
1$ terraform fmt -check -diff -recursive
2main.tf
3--- old/main.tf
4+++ new/main.tf
5@@ -1,13 +1,13 @@
6 terraform {
7-required_version = ">= 1.5"
8+ required_version = ">= 1.5"
9 }
10 variable "name" {
11-type = string
12-default= "demo"
13+ type = string
14+ default = "demo"
15 }
16 locals {
17 tags = {
18 Name = var.name
19- environment = "dev"
20+ environment = "dev"
21 }
22 }
23modules/net/vpc.tf
24--- old/modules/net/vpc.tf
25+++ new/modules/net/vpc.tf
26@@ -1,4 +1,4 @@
27 variable "cidr" {
28- type = string
29- default = "10.0.0.0/16"
30+ type = string
31+ default = "10.0.0.0/16"
32 }
33(exit code 3)
Without -check, the same command rewrites the files and lists them, with exit 0:
1$ terraform fmt -recursive
2main.tf
3modules/net/vpc.tf
4$ terraform fmt -check -recursive
5$ echo $?
60
Which files fmt touches
The docs say .tf, .tfvars and .tftest.hcl are updated and JSON files are not. I checked with one file of each kind, all badly formatted except the JSON one:
1$ terraform fmt -check -diff
2a.tftest.hcl
3--- old/a.tftest.hcl
4+++ new/a.tftest.hcl
5@@ -1,3 +1,3 @@
6 run "a" {
7-command = plan
8+ command = plan
9 }
10list.auto.tfvars
11@@ -1,4 +1,4 @@
12 x = [
13-"a",
14- "b",
15- ]
16+ "a",
17+ "b",
18+]
19prod.tfvars
20@@ -1,2 +1,2 @@
21-region="eu-central-1"
22-instance_type = "t3.micro"
23+region = "eu-central-1"
24+instance_type = "t3.micro"
25$ terraform fmt -check
26$ echo $?
270
The .auto.tfvars file also had its closing bracket moved to column 0 (that is the canonical style), and j.tf.json was left exactly as I wrote it ({"variable":{"x":{"type":"string"}}}), so a JSON-generated configuration never fails the check. The second command ran after terraform fmt rewrote the three files, which is why it printed nothing and exited 0.
Recursive, stdin and a syntax error
My first terraform fmt -check in the project root listed only main.tf and missed modules/net/vpc.tf. That is the documented default: only the current directory is processed, and -recursive adds subdirectories. A CI job without -recursive will pass while a module is badly formatted, which is the most common mistake I see.
Standard input works with a single dash, and formats whatever you pipe in:
1$ printf 'variable "x" {\ntype=string\n}\n' | terraform fmt -
2variable "x" {
3 type = string
4}
fmt needs valid syntax, so an incomplete file stops it with exit code 2 and a normal parser error rather than a format result:
1$ terraform fmt -check
2Error: Invalid expression
3 on bad.tf line 2, in variable "x":
4 2: type =
5Expected the start of an expression, but found an invalid expression token.
6(exit code 2)
So the exit codes I observed are 0 (clean), 2 (cannot parse) and 3 (needs formatting). Treat anything non-zero as failure, but know which one you are looking at when you read a log.
A pre-commit hook that blocks unformatted code
The pre-commit framework (version 4.7.0 here) runs hooks on git commit. A repo: local hook needs no external repository. This is the file I used:
1repos:
2 - repo: local
3 hooks:
4 - id: terraform-fmt
5 name: terraform fmt -check
6 entry: terraform fmt -check -diff
7 language: system
8 files: '\.tf$'
9 pass_filenames: false
With an unformatted main.tf staged, the commit was refused and the diff printed:
1$ git commit -m "add variable"
2terraform fmt -check.....................................................Failed
3- hook id: terraform-fmt
4- exit code: 3
5
6main.tf
7--- old/main.tf
8+++ new/main.tf
9@@ -1,4 +1,4 @@
10 variable "name" {
11-type = string
12-default= "demo"
13+ type = string
14+ default = "demo"
15 }
After terraform fmt and git add, the same commit printed Passed and went through. pass_filenames: false is deliberate: terraform fmt takes directories, and passing it file names from several folders is not what I want.
The same check in GitHub Actions
I did not run this workflow, so treat it as a template and not as output. The HashiCorp GitHub Actions tutorial uses hashicorp/setup-terraform followed by a format step, and the workflow syntax reference covers the keys below:
1- uses: hashicorp/setup-terraform@v3
2- run: terraform fmt -check -diff -recursive
A non-zero exit code fails the step, which fails the check on the pull request.
What broke when I ran this
--no-coloris rejected. I typedterraform fmt -check -diff -recursive --no-colorand gotError parsing command-line flags: flag provided but not defined: -no-color, followed by the whole usage text. The documented spellingterraform fmt -no-colorworks. A globalterraform -no-color fmtfails too withInvalid flags before the subcommand. Use the single-dash form afterfmt; withNO_COLOR=1set in the environment the file list printed as plainmain.tfwith no escape bytes (I checked withod -c).-list=falseswallows the diff too. I expectedterraform fmt -check -list=false -diffto print only the diff. It printed nothing at all and still exited with code 3, so a CI log with that combination fails with no explanation. Keep the file list on when you use-check.- A clean root hides a dirty module when you forget
-recursive, as described above. - The docs say "non-zero"; the real value is 3. Do not hard-code 1 in a script.
Options table
| Option | Effect | Value I observed |
|---|---|---|
-check | Never writes; lists unformatted files | exit 3 when files differ, 0 when clean |
-diff | Prints a unified diff | combine with -check |
-recursive | Also scans subdirectories | needed for modules/ |
-list=false | Do not print file names | for diff-only output |
-write=false | Do not write files | implied by -check |
- as target | Read from standard input | output goes to standard output |
Timing, measured with date around the command: terraform fmt -check -recursive took 0.036 s to 0.050 s on my 2-file project, and 0.048 s on a tree of 200 module folders with one 3-line file each. The terraform binary itself is 123 MB. A whole git commit with the pre-commit hook installed took 0.32 seconds. Formatting is never the slow part of a pipeline, so there is no reason to skip it.
Read More - Terragrunt -
Did this save you a debugging session? Stay in the loop -
- Subscribe on YouTube - every post here has a screen-recorded companion video.
- Code on GitHub - the repositories, Terraform and scripts behind these posts.