Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 3

Remote state, environments and the checks every plan should pass

Keep state in a locked, encrypted remote backend, give each environment its own state and credentials, and check every plan before it is applied.

Contentsand lesson path

What you will learn

  • Keep state in a locked remote backend, separate environments, and review a plan to catch destructive or unintended changes before applying.

01. Keep state in a shared, locked backend

Without a backend setting, tofu apply writes state to a local file, terraform.tfstate. Small teams sometimes commit that file to Git so that everyone has a copy. That causes two serious problems:

  • Lost updates. If Alice and Bob apply at the same time from their own clones, each writes a different state file, and whoever pushes last overwrites the other's record. The resources Bob created still exist in the cloud, but state no longer knows them, so OpenTofu will neither manage nor destroy them. They become orphans that keep costing money.
  • Secrets in clear text. State stores every attribute of every managed resource, including database passwords, private keys and tokens that a provider generated. Anyone who can read the repository can read them.

The fix is a remote backend with locking, such as an S3 bucket, Google Cloud Storage or HCP Terraform. Two properties make it safe:

  1. One shared copy. State lives in a bucket with encryption and versioning turned on, so every earlier version of the state is kept and can be restored.
  2. A lock. Before a plan or apply, OpenTofu takes a lock in the backend. The S3 backend can keep the lock as a small object next to the state in the same bucket (use_lockfile = true, available since Terraform 1.10 and OpenTofu 1.10); older setups use a DynamoDB table, which Terraform has deprecated and OpenTofu still fully supports. While one run holds the lock, a second run stops with Error acquiring the state lock, or waits up to the time you give with -lock-timeout, instead of writing over the first.

To move existing local state into a new backend, add the backend block and run tofu init -migrate-state. OpenTofu detects the change, asks you to confirm and copies the state into the bucket, so nobody edits state files by hand.

02. Separate environments to limit the blast radius

A common mistake is one configuration and one state file for dev, staging and production, with conditions such as var.env == "prod" deciding what to create. A mistake made while testing dev is then applied by the same run that manages production, and one bad plan can change both.

Most teams give each long-lived environment its own state:

  • A directory per environment. The repository has folders such as environments/dev, environments/staging and environments/prod. Each folder sets its own state key (services/web/dev.tfstate, services/web/prod.tfstate) and calls the same shared modules with different inputs.
  • Separate credentials. Each environment gets its own deployment role, ideally in its own cloud account. With separate state and separate credentials, an accidental destroy in the dev folder cannot read or change production: it has neither the production state nor the right to call the production account.

CLI workspaces (tofu workspace new staging) are another way to keep several states for one folder. They switch only the state file: the code, the backend settings and the provider credentials stay the same. An engineer who means to destroy a dev environment but forgot to switch workspaces destroys whatever the current workspace manages, which may be production. Workspaces also make it hard to give environments different provider versions or settings. So many teams use workspaces for short-lived copies, such as one preview environment per pull request, and directories for permanent environments.

The backend block below stores production state in S3 with encryption and S3-native locking.

HCL · Declaring an encrypted remote S3 backend with S3-native state locking
terraform {
  required_version = ">= 1.10.0" # use_lockfile needs 1.10 or later

  # Remote backend with strict locking and encryption
  backend "s3" {
    bucket       = "corp-terraform-state-prod"
    key          = "services/web/production.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true # lock object next to the state; no DynamoDB table
  }
}

03. Check every plan before it is applied

Before anyone applies a plan, a person and automated checks in CI should look at it. Four checks catch most problems:

  1. Read the summary line. Plan: X to add, Y to change, Z to destroy. If a pull request that should only change an environment variable shows 1 to destroy, stop and find out what would be deleted and why.
  2. Look for replacements (-/+). Some attributes cannot change in place. Turning on storage_encrypted for an existing RDS instance, or moving an EBS volume to another availability zone, makes the plan mark the attribute # forces replacement: OpenTofu would destroy the old object and create a new, empty one. For a database or a disk, that deletes the data unless a migration is planned.
  3. Run policy checks. Scanners such as trivy config, Checkov or Open Policy Agent test the configuration or the plan as JSON (tofu show -json tfplan) against rules, for example: no security group open to 0.0.0.0/0 on port 22, required cost tags present, encryption at rest turned on. A broken rule fails the CI job before anyone approves.
  4. Plan in the pull request. Tools such as Atlantis, or a GitHub Actions workflow, run tofu plan -out=tfplan when a pull request opens and post the plan as a comment, so reviewers discuss the actual change before merging. Only values marked sensitive are redacted in that output, by the provider schema or by sensitive = true on your variables and outputs. A secret in an attribute that is not marked sensitive, such as user_data, a rendered template or a data source result, appears in clear text for every reader of the repository. Mark secret variables and outputs sensitive, keep secrets out of other attributes, and never upload the binary plan file where untrusted readers can fetch it: it holds every value unredacted.

04. Check your understanding

Practice check · 3 questions

Remote state backends, environment isolation, and plan review check

Three questions on state locking, workspaces and secrets in plan output.

Q1. Two CI jobs run `tofu apply` against the same S3 backend with `use_lockfile = true` at the same moment. What happens?
Q2. Why does the lesson keep permanent environments in separate directories rather than in CLI workspaces?
Q3. A pipeline posts `tofu plan` output as a pull request comment. A template renders a database password into an instance's `user_data`, which is not marked sensitive. What do readers see?
Practice only: not graded, not saved, not evidence.

05. Apply it

Check your own repositories against these points:

  • *.tfstate and *.tfstate.* are in .gitignore, and every environment uses an encrypted remote backend.
  • The backend locks (for S3, use_lockfile = true), and CI waits for a held lock with -lock-timeout instead of failing at once.
  • Each permanent environment has its own state, its own folder and its own deployment credentials.
  • A plan that destroys or replaces a database, a disk or a bucket needs an extra, named approver.
  • CI runs a policy scanner on every plan and fails the job on any rule it breaks.

06. Review prompt

Without looking back, explain the two problems that come from keeping state in Git and how a remote backend with a lock solves each. Compare a directory per environment with CLI workspaces: what do they share, and what can go wrong? Then list the four checks a reviewer makes before approving a plan.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check