Learning Objectives
By the end of this chapter, you will be able to:
- Describe how the local backend stores state on disk, where it places workspace files and backups, and the safety properties it does and does not provide.
- Describe the state-locking protocol, identify which backends implement it, and explain how
-lock,-lock-timeout, andforce-unlockinteract with the lock file. - Configure remote state through the
backendblock, including partial configuration with-backend-config, migrations oninit, and cross-state reads through theterraform_remote_statedata source. - Detect and manage resource drift through
terraform plan -refresh-onlyandterraform apply -refresh-only, and use theterraform statesubcommands to inspect, move, and remove individual resource instances.
Executive Summary
- Terraform state is the source of truth that maps every HCL address to a real resource; the backend type decides where that file lives, who can write it, and whether two operators can run at the same time without corrupting it.
- The local backend writes
terraform.tfstateto the working directory and protects it with a host-level.terraform.tfstate.lock.infoadvisory file; that lock holds inside a single machine and does not extend across a team. - Remote backends, declared inside a
backendblock in theterraformblock, move state to a shared store such as S3, Azure Blob Storage, or GCS, where they can offer team-wide locking, encryption at rest, and object versioning. - Drift, the divergence between recorded state and the real world, is detected through the refresh phase and reconciled with
-refresh-onlyruns; the documentedterraform statesubcommands let you inspect, move, replace, and evict resource instances without touching infrastructure.
Assumptions
- The reader understands the Write -> Plan -> Apply workflow, the role of providers, and the modules layer covered in earlier chapters.
- Examples target Terraform 1.12 with a generic provider surface (random, local, null) and an illustrative AWS S3 backend, since the exam is provider-agnostic and the S3 backend is the most heavily documented remote backend in the official guide.
- File names, directory layout, and CLI output match the official Terraform CLI documentation for the 1.12 stable release; alternate paths set through
-stateor-state-outare noted inline where they change behaviour.
