Language

Variables & State · Lesson 10 of 30

State File Basics

Source: doonops-curriculum/variables-state--state-basics.md

Doonops lesson

Goal

Understand state file — Terraform's memory of what it created.

Simple explanation

State = notebook where Terraform writes "I created server i-abc123". Without it, Terraform forgets and tries duplicate.

Technical view

terraform.tfstate JSON maps address to real IDs; state mv/rm; remote backend S3; locking DynamoDB.

Think of it like

Sticker on each box in warehouse — Terraform scans stickers next time instead of buying new boxes.

Steps

  1. Read simple section
  2. Read analogy + diagram
  3. Copy project files
  4. Do local lab

Deep explanation

Layman words first, then technical detail — read slowly

Why state exists

Cloud has real IDs (i-0abc...). Your .tf files only have logical names (aws_instance.app). State connects them.

main.tf says: aws_instance.app
state says:  aws_instance.app = i-0abc123 in ap-south-1
AWS has:       real running server i-0abc123

Rules

  • Do not edit .tfstate by hand unless expert
  • Do not commit state to public Git (has secrets sometimes)
  • Team uses remote state (later module)

Useful commands

terraform state list
terraform show
terraform state show aws_instance.app

Example (Doonops)

Modern HCL — names are examples, not from any third-party course

Example HCL
HCL
# terraform state list
# terraform show

Terraform runs on your computer — copy this HCL into a folder, then follow the local lab steps below.

Check

  • Why state needed
  • Why not commit state to GitHub

Project files for this lab

Full implementation folder — copy all files, then run terraform commands

Lab project files (full folder)

Copy every file below into one folder — same as a real repo module. Then run the local lab steps.

Suggested folder: Suggested path: ~/doonops-terraform/07-state/

versions.tfSee file purpose in the code below
terraform {
  required_version = ">= 1.9.0"
}

Module check — did you get it?

2–3 quick questions before the next module

Variables & state — quick check

Quick check — did this module stick?

1. Where should terraform.tfstate live in a team?

  • Email attachment
  • Remote backend (e.g. S3)
  • Public website
  • Only on one laptop forever

2. Outputs are used to…

  • Hide secrets
  • Expose values after apply (IDs, URLs)
  • Delete resources
  • Skip plan