Overview

6 State Management

This chapter explains why Terraform is a stateful system and what that means in practice. State links configuration to real-world resources using stable identifiers, avoiding fragile discovery heuristics and enabling faster plans, richer features, and simpler provider development. Keeping state also unlocks “state-only” workflows where resources exist purely in state to generate data or logic (for example, random values, TLS assets, null/terraform_data helpers). The tradeoff is that teams must manage state as critical data: it accelerates iteration and supports advanced patterns, but it must be stored, protected, and operated with care.

The chapter details three pillars for state backends—reliability, security, and availability—and shows how local state is for development only. It surveys built-in backends (S3, GCS, AzureRM, Consul, PostgreSQL, Kubernetes, HTTP, and cloud/TACOS options), calls out essentials like encryption, locking, auditing, and backups, and covers backend configuration patterns, partial configs, environment-based auth, and the Cloud block (including remote execution and workspace behavior differences between vendors and Terraform/OpenTofu). It dissects state’s JSON structure (version, terraform_version, serial, lineage, resources, outputs, checks), explains migrations and upgrades, and clarifies the two flavors of “workspaces,” emphasizing where confusion commonly arises.

For day‑to‑day operations, the chapter recommends backing up with state pull/push, using code-first moves and removals (moved/removed blocks), falling back to CLI tools for specific cases, and treating manual edits as a last resort. It classifies state drift causes (accidental or intentional manual changes, expected external/automated changes, and Terraform/back-end faults) and suggests responses like refresh-only plans, lifecycle ignore_changes, imports, and strong operational hygiene. For cross-project composition, it presents terraform_remote_state (with defaults), guidance to keep lookups at the root or in thin adapters, and alternatives such as provider data sources or explicit variables. It closes with practical patterns for state-only providers: Random (keepers and sensitive outputs), Time (static/offset/rotating/sleep), Null, and the built-in terraform_data as a modern, provider-free replacement for testing flows, triggering replacements, and orchestrating provisioners.

Basic Backend Configuration Requirements
Types of State Drift
An example of how organization structure can mirror module ownership.

Summary

  • Terraform uses State to reduce complexity, improve performance, and provide functionality such as remote state viewing and state only resources.
  • When working with teams a centralized state storage solution is essential, and this is provided by Terraform Backends.
  • Terraform Backends are generally chosen from technology teams are already using, or through the use of specialized Terraform CICD tools.
  • State Drift occurs when the Terraform state does not match the real world infrastructure.
  • State can be accessed across projects, allowing the outputs from one project to be used in another project.
  • State only resources enable the use of data, such as the time or even random numbers, to be generated in a Terraform centric way.

FAQ

Why do Terraform and OpenTofu require state?State lets Terraform/OpenTofu reliably map configuration to real-world resources using stable identifiers (for example, AWS ARNs) even when tags or names change. Keeping state reduces engine and provider complexity versus “discovering” resources on every run, and it dramatically improves performance by avoiding full-environment scans. It also enables powerful features such as state-only resources.
What are the most important backend considerations: reliability, security, and availability?- Reliability: Choose durable storage with versioning where possible, and keep tested, off-platform backups. Plan your restore process in advance.
- Security: Enforce least-privilege access, MFA, encryption at rest/in transit, and access logging; never expose state publicly. Minimize sensitive values in state via secret managers where feasible.
- Availability: Treat state as critical infrastructure; target “four nines” or better uptime with clear vendor SLAs. If state is down, deployments stop.
What’s inside a tfstate file and what do version, lineage, and serial mean?A state file (JSON) includes: version (state schema version), terraform_version (tool version that last wrote state), lineage (a project-unique UUID created at first init), serial (monotonically increasing number per saved state), resources (with module/type/name, provider, instances, and attributes), outputs (root module outputs only), and check_results (results of check assertions). Sensitive values are still stored in state even if marked sensitive.
Which backend should I use, and what features must it support?Use the local backend only for development. For teams, pick a remote backend that aligns with your platform and skills (S3+DynamoDB locking, GCS, AzureRM, Consul, PostgreSQL, Kubernetes Secrets, or TACOS via cloud/remote). Ensure it supports locking, strong durability, audit logging, encryption, and adequate availability. Favor the tech your org already operates well.
How do I configure and authenticate a backend safely?Define a backend block only in the root module; prefer partial configuration and supply the rest via -backend-config files or environment variables rather than hard-coding secrets. Enable locking, encryption, access logging, and tight IAM. Remember backend config is cached under .terraform. For the cloud block (TACOS), authenticate with terraform login against the configured hostname and avoid embedding credentials.
How can projects share data across states?Use the built-in terraform_remote_state data source to read another project’s exported root outputs via its backend configuration. Ensure the producer exposes the needed outputs. Consider defaults to soften dependencies when the remote isn’t ready. Good patterns include keeping terraform_remote_state in the root module (pass values into child modules) or wrapping it in internal “lookup” modules. Alternatives: provider data sources (preferred when possible) or explicit input variables. Be mindful that remote state access also exposes sensitive attributes.
How do workspaces work, and how do Cloud/TACOS workspaces differ?CLI workspaces create multiple, separate state instances for the same code and expose terraform.workspace for conditional logic. Under the cloud block (e.g., HCP Terraform, Scalr, env0), “workspaces” refer to remote environments managed by the service; the terraform workspace command interacts with those remote contexts (tag-based or name-based selection), and semantics differ from local CLI workspaces.
What’s the safe way to change state without changing real infrastructure?Always back up first with terraform state pull; restore with terraform state push (use -force only when necessary). Prefer code-driven changes: use moved blocks to rename/relocate resources and removed blocks to de-adopt resources without destroying them. CLI utilities help in special cases: terraform state rm (remove from state), terraform state replace-provider (swap provider addresses). Avoid manual editing except as a last resort.
What is state drift and how should I handle it?Drift happens when real infrastructure changes outside Terraform. Investigate root cause, then fix accordingly: accidental manual changes (apply plan to revert), intentional emergency changes (encode them in code before next run), expected automated changes (use lifecycle ignore_changes or refresh-only plans), and Terraform/tooling errors (import or delete stray resources; restore from backups if state is corrupt). Audit logs and team communication are key.
What are state-only providers/resources and when should I use them?State-only resources compute values and persist them in state without external APIs. Examples: Random (e.g., random_password with cryptographic RNG; use keepers to rotate), Time (time_static/offset/rotating, plus time_sleep to delay), Null (null_resource no-op for testing), and terraform_data (built-in modern replacement for null_resource; triggers_replace; can drive replace_triggered_by or run provisioners). Treat generated sensitive values as sensitive in state and secure the backend accordingly.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Terraform in Depth ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Terraform in Depth ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Terraform in Depth ebook for free