# fmt, validate and TFLint

Three fast checks that need no cloud account: terraform fmt for style, terraform validate for correctness, and TFLint for mistakes the other two miss, such as an invalid AWS instance type.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 7. About 20 minutes, beginner. Source: https://devops.rajeev.pro/courses/terraform/07-format-validate

## What you will learn

- Format files with terraform fmt and check formatting in CI with -check
- Catch typos and undeclared references with terraform validate
- Run TFLint with the AWS ruleset and read its findings
- Put all three in the right order in a pipeline, and use their exit codes

> **Lab status.** **Verified lab:** terraform fmt, both validate errors and TFLint 0.65.0 with the AWS ruleset. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** none. <br />**Cloud lab:** none; nothing here needs a cloud account.

A `terraform plan` against a real cloud takes time and needs credentials. Before it, three checks
run in seconds and catch most silly mistakes: formatting, invalid code and suspicious values. They
need **no cloud credentials and no live infrastructure**, which makes them the first jobs in every
Terraform pipeline.

What they do need, to be precise: `terraform fmt` needs nothing at all. `terraform validate` needs the
providers installed, so on a clean machine `terraform init` downloads them from the registry first,
and `tflint --init` downloads its rule plugins. After that one download (or with a provider cache),
all three run without network access.

> **Figure.** Three checks from cheapest to deepest. terraform fmt checks style only: indentation and alignment, -check exits 3 if not formatted, -diff shows the change, -recursive covers every folder. terraform validate asks whether it is valid Terraform: syntax and block structure, argument names, undeclared variables; it needs init for provider schemas. tflint asks whether it is a good idea: t3.mirco is invalid, unused variables, missing required_version, provider rule sets for AWS and others.
>
> fmt, then validate, then tflint: free, fast, and no cloud credentials needed.

## terraform fmt

`terraform fmt` rewrites `.tf` files into the one official style: two-space indentation and aligned
equals signs. There's nothing to configure, which ends every style argument in code review.

```sh
$ cat main.tf
resource "local_file" "note" {
filename="${path.module}/note.txt"
    content =   "hello"
}
$ terraform fmt -check; echo "exit code $?"
main.tf
exit code 3
$ terraform fmt -diff
main.tf
--- old/main.tf
+++ new/main.tf
@@ -1,4 +1,4 @@
 resource "local_file" "note" {
-filename="${path.module}/note.txt"
-    content =   "hello"
+  filename = "${path.module}/note.txt"
+  content  = "hello"
 }
$ terraform fmt -check; echo "exit code $?"
exit code 0
```

- `terraform fmt` (no flags) fixes the files in place and lists the ones it changed.
- `-check` changes nothing and exits non-zero (here 3) if anything needs formatting: use it in CI.
- `-diff` shows what it changed. `-recursive` also covers subfolders such as `modules/`.

Most editors run fmt on save with the official HashiCorp extension. Do that, and CI never fails on
style.

## terraform validate

`validate` checks that the configuration is **valid Terraform**: correct syntax, real argument names
for each resource type, references that point at something that exists, and matching types. It
reads the provider schemas, so run `terraform init` first. It doesn't contact your cloud.

A typo in an argument name:

```text
$ terraform validate

Error: Unsupported argument

  on main.tf line 3, in resource "local_file" "note":
   3:   contents = "hello"

An argument named "contents" is not expected here. Did you mean "content"?
```

A variable that was never declared:

```text
$ terraform validate

Error: Reference to undeclared input variable

  on main.tf line 3, in resource "local_file" "note":
   3:   content  = var.message

An input variable with the name "message" has not been declared. This
variable can be declared with a variable "message" {} block.
```

After declaring `variable "message"`:

```sh
$ terraform validate
Success! The configuration is valid.
```

What validate **can't** know: whether `t3.mirco` is a real instance type, whether a bucket name is
free, or whether you have permission. Those are values, not structure, and need a linter or a real
plan.

## TFLint

**TFLint** is a separate open-source linter. It adds rules about values and good practice, and
**plugins** with rules per cloud. The lab used TFLint 0.65.0 with the AWS ruleset on this deliberately
flawed file:

```hcl
# .tflint.hcl
plugin "aws" {
  enabled = true
  version = "0.50.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}
```

```hcl
# main.tf (excerpt)
variable "unused_region" {
  type = string
}

resource "aws_instance" "web" {
  ami           = "ami-0f58b397bc5c1f2e8"
  instance_type = "t3.mirco" # typo
}
```

```text
$ tflint --init
Installing "aws" plugin...
Installed "aws" (source: github.com/terraform-linters/tflint-ruleset-aws, version: 0.50.0)
$ tflint --format=compact
3 issue(s) found:

main.tf:16:19: Error - "t3.mirco" is an invalid value as instance_type (aws_instance_invalid_type)
main.tf:1:1: Warning - terraform "required_version" attribute is required (terraform_required_version)
main.tf:10:1: Warning - variable "unused_region" is declared but not used (terraform_unused_declarations)
```

`terraform validate` passes this file: `instance_type` is a correctly named argument holding a
string. Only TFLint knows `t3.mirco` isn't a real type. Without it you'd find out at apply time,
halfway through creating other resources. The two warnings come from TFLint's built-in Terraform
rules. Exit code 2 means issues were found, so CI fails.

> **Security scanners are the next step.** Trivy and Checkov look at the same files for security problems, such as a public S3 bucket or SSH open to the world. They're covered in the Security lesson and run in the same CI job.

## Mission: Write one script that runs every pre-plan check

Write check.sh that runs terraform fmt -check -recursive, terraform init -backend=false, terraform validate and tflint in order, and stops at the first failure. Run it on a project with a formatting problem, then fix it and run again.

- You need: Any Terraform project
- You'll have: check.sh

```sh
$ cat > check.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
terraform fmt -check -recursive
terraform init -backend=false -input=false >/dev/null
terraform validate
tflint --init >/dev/null && tflint --format=compact
EOF
$ chmod +x check.sh && ./check.sh; echo "exit code $?"
```

`-backend=false` lets validate run without access to the real state, which is what CI wants for a
quick check. The script should stop at fmt with exit code 3 until the files are formatted, then pass
through to TFLint.

## Try it

- Break the indentation of a .tf file, run `terraform fmt -diff`, and read the change.
- Run `terraform fmt -check` and print `$?` before and after formatting.
- Misspell an argument name and run `terraform validate`.
- Install TFLint, add the AWS plugin, and lint a resource with `instance_type = "t3.mirco"`.
- Do the mini mission and keep `check.sh`.

## Quiz

1. `terraform fmt -check` exits with code 3. What does it mean?
   - The configuration is invalid
   - **At least one file isn't formatted; nothing was changed** (answer)
   - Terraform crashed
   Why: With -check, fmt only reports. A non-zero exit code makes a CI job fail until someone runs terraform fmt.

2. Which mistake does terraform validate catch?
   - An instance type that doesn't exist in AWS
   - **An argument named contents instead of content** (answer)
   - A bucket name already taken by someone else
   Why: validate checks syntax and names against the provider schema. It doesn't call the cloud, so it can't know which instance types or names exist; TFLint and plan cover more.

3. Why does terraform validate need terraform init first?
   - It doesn't
   - **It needs the provider schemas, which come with the downloaded providers** (answer)
   - It uploads the code to HashiCorp
   Why: Argument names and types are defined by each provider. Without the providers installed, validate can't check them.

## Resources

- [terraform fmt command](https://developer.hashicorp.com/terraform/cli/commands/fmt) (HashiCorp)
- [terraform validate command](https://developer.hashicorp.com/terraform/cli/commands/validate) (HashiCorp)
- [TFLint](https://github.com/terraform-linters/tflint) (terraform-linters on GitHub)
- [TFLint AWS ruleset](https://github.com/terraform-linters/tflint-ruleset-aws) (terraform-linters on GitHub)
- [Terraform style guide](https://developer.hashicorp.com/terraform/language/style) (HashiCorp)
