6: Terraform state management

    Describe the local backend

    When you run terraform init in a brand-new working directory that does not declare a backend, Terraform installs the local backend by default. This is the simplest documented backend and the one most engineers first meet: state is a JSON file on disk, and every operation reads and writes that file directly. Knowing its precise behaviour matters because most production incidents around team-based state start with someone treating local state as if it were shared infrastructure.

    The local backend stores its state in a single file named terraform.tfstate, placed in the working directory next to your .tf files. The file is plain JSON: it contains a version field that tracks the state-format schema, a terraform_version field that records the CLI version that last touched it, the serial counter introduced in an earlier chapter, the lineage UUID that distinguishes one state's history from another, and a resources array that lists every managed resource instance with the attributes the provider reported. Provider-returned data is written verbatim. Values you marked sensitive = true are stored in clear text inside the file; the sensitive flag only redacts CLI output, it does not encrypt anything in the state. If terraform.tfstate lands in version control or in an unencrypted backup bucket, every secret it contains lands there too.

    Each successful apply rewrites the file in place. Just before the new state is committed, Terraform renames the previous version to terraform.tfstate.backup, so the local backend keeps exactly one backup generation, no more. There is no automatic rotation, no timestamped history, and no built-in pruning. The CLI also produces a transient terraform.tfstate.tmp while it is writing, which is atomically renamed on success. If apply crashes between the write and the rename you may find that tmp file on disk; the official documentation calls out that the most recent in-flight write lives there and that recovery often means inspecting both files by hand.

    Where the local backend lives on disk

    The default layout in a working directory that has been initialised once and applied once looks like this:

    .
    ├── main.tf
    ├── variables.tf
    ├── outputs.tf
    ├── .terraform/
    │ ├── providers/
    │ ├── modules/
    │ └── terraform.tfstate # backend metadata only, NOT resource state
    ├── .terraform.lock.hcl # dependency lock file
    ├── terraform.tfstate # the real state file
    └── terraform.tfstate.backup # previous generation, exactly one
    

    Two paths in that tree are easy to confuse. The terraform.tfstate at the root of the working directory is the resource state: it maps every HCL address to provider attributes and is what every plan reads and every apply rewrites. The .terraform/terraform.tfstate inside the hidden .terraform/ directory is backend metadata. It records which backend the working directory was initialised against and, for backends that operate remotely, where to find the real state. With the local backend the inner file effectively says "the backend is local and the state lives in the working directory"; with a remote backend it records the backend's identity so subsequent runs know to talk to S3 or HCP Terraform rather than the working directory. Deleting the inner file forces a re-init; deleting the outer file is destructive and will make Terraform believe nothing exists.

    The local backend accepts two arguments that change those paths. path controls where the state file lives, and workspace_dir controls where non-default workspaces' state files live. Both default to the working directory.

    terraform {
     backend "local" {
     path = "state/prod.tfstate"
     workspace_dir = "state/workspaces"
     }
    }
    

    In that configuration the default-workspace state ends up at state/prod.tfstate and any extra workspace named staging ends up at state/workspaces/staging/terraform.tfstate. The CLI flags -state and -state-out on plan, apply, and destroy can override those locations for a single command, but they are documented as legacy options for special-purpose scripts and are not the supported way to manage state long-term.

    Workspaces and the terraform.tfstate.d directory

    The local backend supports the workspace feature introduced in earlier Terraform releases. When you run terraform workspace new staging, the backend creates a directory named terraform.tfstate.d/staging next to the working directory and stores terraform.tfstate inside it. Switching back with terraform workspace select default moves the active state pointer back to the root file. Every workspace has its own independent state file with its own serial and lineage; they share only the configuration HCL.

    terraform workspace new staging
    terraform workspace new production
    terraform workspace list
    # default
    # * production
    # staging
    terraform workspace select default
    terraform workspace delete staging # fails if the workspace still has resources
    

    💡 Exam Trap: Local workspaces are stored on the same machine in the same working directory tree. They are not the same concept as HCP Terraform workspaces, which are server-side resources with their own state, variables, and run history. Questions that frame "workspaces give a team a shared, lockable state per environment" are conflating the two; the local-backend workspaces give you per-environment files on one disk, not team coordination.

    Locking on the local backend

    The local backend implements an advisory, single-host lock through a file named .terraform.tfstate.lock.info. When a CLI invocation needs to read or write state it tries to create that file; if the file already exists the CLI refuses to proceed and reports the lock holder. The contents of the lock file are a small JSON document with the lock ID, the operation, who held it, and a timestamp. Because this lock lives on the local filesystem it protects against two terraform apply invocations on the same workstation but does nothing for two engineers on two laptops both pointing at the same state file over a shared network drive. The next section of this chapter walks through state locking proper; the point here is that on the local backend the lock is host-scoped.

    Performance and operational properties

    The local backend reads and writes the entire state file on every operation. There is no incremental update protocol; the file is always rewritten as a whole. For a few dozen resources this is instant; for thousands of resources you will notice the rewrite latency, although the bottleneck almost always shifts to the refresh phase well before the disk write becomes interesting. There is no built-in compaction or pruning, no historical view, and no way to roll back beyond the single .backup generation.

    Operational hygiene with the local backend is mostly about three things: not committing state to git, having a backup story that captures both terraform.tfstate and terraform.tfstate.backup, and rotating credentials when state files are exposed. The first one trips up new teams the most: the file looks like a normal source artefact, it is plain JSON, and it sits in the working directory next to main.tf. Every official guide and the Terraform documentation repeats the warning that state is sensitive and must be excluded from version control. A working .gitignore for a Terraform project starts with:

    # Local Terraform state files
    *.tfstate
    *.tfstate.*
    .terraform.tfstate.lock.info
    
    # Plugin and module caches
    .terraform/
    
    # Variable files that may carry secrets
    *.tfvars
    *.tfvars.json
    

    📊 Limit: The local backend keeps exactly one backup generation per workspace. The previous terraform.tfstate is renamed to terraform.tfstate.backup on each successful apply, and the prior backup is overwritten. There is no automatic timestamped history. If you need point-in-time recovery you must implement an external backup strategy, or move to a backend whose underlying store offers object versioning.

    When the local backend is the right choice

    The local backend is genuinely appropriate for three workloads. The first is learning and prototyping: one engineer, throwaway resources, no team coordination required. The second is single-operator personal infrastructure where the engineer accepts that they are the only writer. The third is a CI-only pattern where state lives transiently on the CI runner because the runner builds, applies, destroys, and exits, and no state is ever shared between runs. Anything beyond that, especially anything involving more than one human writer, demands a remote backend with real locking. The exam tests this distinction with scenarios that describe two engineers and a shared state file; the right answer is always to move to a remote backend, not to wrap the local backend in any kind of synchronisation script.

    Implementing a local-backend project end to end

    A minimal working configuration looks like this:

    terraform {
     required_version = ">= 1.12.0"
    
     required_providers {
     random = {
     source = "hashicorp/random"
     version = "~> 3.6"
     }
     }
    
     # Explicit local backend declaration. Equivalent to omitting the
     # backend block entirely; included here for clarity.
     backend "local" {
     path = "terraform.tfstate"
     }
    }
    
    resource "random_pet" "team_name" {
     length = 2
     separator = "-"
    }
    
    output "name" {
     value = random_pet.team_name.id
    }
    

    Running through the workflow once produces:

    terraform init
    terraform plan -out=tfplan
    terraform apply tfplan
    cat terraform.tfstate | jq '.resources[0]'
    # Inspect the random_pet attributes that were just written.
    
    terraform destroy -auto-approve
    ls -la terraform.tfstate*
    # terraform.tfstate is now empty of resources
    # terraform.tfstate.backup contains the prior state
    

    ⚠️ Anti-Pattern: Sharing a terraform.tfstate file by checking it into git or syncing it through Dropbox, OneDrive, or a network share. The local backend's lock is a host-level advisory file; it cannot coordinate writes across machines, and the JSON merge a VCS performs on a state file is almost always wrong. Two engineers who apply against the same shared local file will overwrite each other's writes, corrupt resource addresses, and end up with state that no longer matches reality. The supported answer is a remote backend.

    🎯 Scenario: An engineer prototypes a small Lambda stack on a laptop with the default local backend. Three weeks later a teammate is asked to add an environment variable. They clone the repo and run terraform plan. Terraform reports that every resource would be created from scratch because the working directory has no terraform.tfstate file: the original author never moved state off the laptop. The recovery path is not to apply (that would create a duplicate Lambda and immediately drift); the right move is to import the existing function into a fresh state on a remote backend the team can share, then continue from there.

    Decision Anchor

    Choose the local backend when there is exactly one writer, when the working directory is ephemeral, or when you are learning. Choose a remote backend (S3, Azure Blob Storage, GCS, HCP Terraform) when more than one human or one CI runner needs to apply against the same configuration, when you need locking that spans machines, when you need encryption at rest you do not have to administer yourself, or when you need point-in-time history beyond the single .backup generation.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the HashiCorp - Terraform Associate learning hub.