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
On this page
- Keep state in a shared, locked backend
- Separate environments to limit the blast radius
- Check every plan before it is applied
- Check your understanding
- Apply it
- Review prompt
Lessons of IaC Fundamentals
- Why infrastructure belongs in code: provisioning, configuration and images Concept · 20 min
- Lab: plan, apply and destroy, then extract a reusable module Lab · 40 min
- Remote state, environments and the checks every plan should pass Concept · 25 min
- Reading a plan like a reviewer: drift, import and state refactoring Worked example · 25 min
- Lab: configure a small fleet idempotently with an Ansible playbook Lab · 30 min
- Check: plan review, drift and configuration scenarios Knowledge check · 10 questions
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:
- 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.
- A lock. Before a
planorapply, 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 withError 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/stagingandenvironments/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
destroyin 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.
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:
- 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 shows1 to destroy, stop and find out what would be deleted and why. - Look for replacements (
-/+). Some attributes cannot change in place. Turning onstorage_encryptedfor 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. - 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 to0.0.0.0/0on port 22, required cost tags present, encryption at rest turned on. A broken rule fails the CI job before anyone approves. - Plan in the pull request. Tools such as Atlantis, or a GitHub Actions workflow, run
tofu plan -out=tfplanwhen 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 bysensitive = trueon your variables and outputs. A secret in an attribute that is not marked sensitive, such asuser_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
05. Apply it
Check your own repositories against these points:
*.tfstateand*.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-timeoutinstead 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.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.