201 β€” Understanding Terraform State

Intermediate

Dive deep into terraform.tfstate to understand how Terraform maps your code to real-world resources and why state matters.

Learning Objectives

1
Understand why Terraform needs state
2
Inspect and navigate state files
3
Use state commands to manage resources
4
Learn state file best practices
Step 1

Create a configuration with multiple resources

Set up a configuration that creates several related resources so we can explore state.

Commands to Run

mkdir -p ~/terraform-practice/lesson-201
cd ~/terraform-practice/lesson-201
cat > main.tf << 'EOF'
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.4"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.5"
    }
  }
}

resource "random_id" "app" {
  byte_length = 4
}

resource "local_file" "config" {
  filename = "${path.module}/app-${random_id.app.hex}.conf"
  content  = "app_id = ${random_id.app.hex}\nenvironment = development"
}

resource "local_file" "readme" {
  filename = "${path.module}/README.txt"
  content  = "Application ID: ${random_id.app.hex}"
}
EOF

What This Does

This configuration uses two providers (local and random) and creates three related resources. The random_id is used by both local_file resources, creating dependencies.

Expected Outcome

A main.tf file with providers and three interconnected resources.

Pro Tips

  • 1
    Dependencies between resources are tracked in state
Was this step helpful?

All Steps (0 / 8 completed)