🎓 A1Learner
🔍
0 of 50 lessons completed

Terraform Best Practices

Best practice is a short checklist that keeps Terraform safe and tidy. Pin versions, keep modules small, and keep one state file per layer.

Pin every version

Pin Terraform and each provider. An unpinned version can change behaviour overnight.

terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.0"
    }
  }
}

One state per layer

Each layer gets its own state file. Dev, staging, and prod never share one.

backend "local" {
  path = "terraform.tfstate"
}

# One backend per layer: dev, staging, and prod each
# keep their own state file, in their own directory.

Destroy after practice

Practice resources cost money and invite drift. Destroy them when the practice ends.

terraform destroy -auto-approve

Example

# main.tf
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.0"
    }
  }

  backend "local" {
    path = "terraform.tfstate"
  }
}

resource "local_file" "checklist" {
  filename = "${path.module}/checklist.txt"
  content  = <<-EOT
    Terraform checklist
    - Versions are pinned.
    - Modules are small and named.
    - One state file per layer.
    - Practice resources are destroyed.
  EOT
}

output "checklist_file" {
  value = local_file.checklist.filename
}

# terraform init
# terraform apply -auto-approve
# terraform destroy -auto-approve

Key points

  • Pin Terraform and provider versions so a run never surprises you.
  • Small modules are easier to read, test, and reuse.
  • One state file per layer limits the blast radius of a mistake.
  • Keep secrets out of config, state, and version control.
  • Destroy practice resources when the practice ends.
  • Review plan output before every apply.

The config follows its own checklist. Versions are pinned, the state path is explicit, and the module is small. The destroy at the end is the last item on the list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why keep one state file per layer?