State & Backends

💤0
Lv 10 XP
← 📜 Infrastructure as Code · Terraform

State & Backends

Intermediate ⭐ 80 XP ⏱ 18 min #terraform#state#backend

Understand Terraform state, remote backends, locking, and how to keep it safe.

📖Theory

Terraform’s state maps your configuration to real resources and stores metadata needed to plan changes. Without it, Terraform can’t tell what already exists or what to update.

By default state is a local terraform.tfstate file — fine solo, unsafe for teams. A remote backend (S3, Azure Storage, GCS, Terraform Cloud) stores it centrally with locking so concurrent applies don’t corrupt it. State can hold secrets, so it must be encrypted and access-controlled — and never committed to git.

🌍Real-World Example
terraform {
  backend "s3" {
    bucket         = "my-tfstate"
    key            = "prod/terraform.tfstate"
    region         = "eu-west-1"
    dynamodb_table = "tf-locks"      # locking
    encrypt        = true
  }
}
terraform state list                 # what Terraform manages
terraform state show aws_s3_bucket.data
terraform import aws_s3_bucket.data my-existing-bucket
✍️Hands-On Exercise
  1. Explain what Terraform state is and why it’s necessary.
  2. Describe two risks of keeping state local for a team.
  3. Configure a remote backend with locking.
  4. Use terraform import (in words) to bring an existing resource under management.
🧾Cheat Sheet
ConceptDetail
StateMaps config → real resources
Local stateterraform.tfstate (solo)
Remote backendS3 / Azure / GCS / TF Cloud
LockingPrevents concurrent corruption
Secrets riskState may hold secrets
state list/showInspect state
importAdopt existing resources
💬Common Interview Questions
What is Terraform state and why does it matter?

A record mapping your configuration to real resources plus metadata for planning. Without it Terraform can’t determine what exists or what to change.

Why use a remote backend with locking?

So a team shares one authoritative state, and locking prevents two simultaneous applies from racing and corrupting it. Remote storage also keeps secrets off laptops.

How do you bring an existing resource under Terraform management?

terraform import <address> <id> records it in state, then you write matching configuration so future plans show no drift.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type