8 Terraform Best Practices for a Safer Workflow

  • DevOps
  • Terraform
  • Intermediate
  • 8 min read

These Terraform best practices protect the one file that knows what your cloud really looks like: the state file. Terraform itself is easy to start with. The trouble begins when a second person joins, a laptop dies, or someone edits state by hand, and these eight habits stop most of those accidents.

Last updated: December 2026

In short

  • Keep state in a shared, locked and versioned place, never only on one laptop.
  • Change state only with terraform commands, and use one state per environment.
  • Keep the code in Git, check every change in CI, and let the pipeline run apply.

What the Terraform State File Does

Terraform reads your .tf files to learn what you want. It reads the state file to learn what it already built: every resource, its ID in the cloud and its settings. When you run terraform plan, Terraform compares the two and shows only the difference.

That makes the state file the memory of your infrastructure. If it is lost, Terraform forgets what it owns and tries to create everything again. If two people change it at once, it can end up broken. Most of the practices below exist to protect it.

State can hold secrets

Passwords and keys that pass through your configuration are saved in the state file as plain text. Treat state like a password file: limit who can read it and keep it encrypted. HashiCorp explains this in its page on sensitive data in state.

The 8 Terraform Best Practices

1. Change State Only With Terraform Commands

The state file is JSON, so it is tempting to open it and fix a value by hand. One wrong bracket or ID, though, and Terraform no longer matches the real resources. Terraform has a command for each safe change instead.

List what Terraform manages:

bash
terraform state list

Show one resource in detail:

bash
terraform state show aws_instance.web

Tell Terraform a resource has a new name in the code, without destroying it:

bash
terraform state mv aws_instance.web aws_instance.app

Stop managing a resource but leave it running in the cloud:

bash
terraform state rm aws_instance.old

Prefer blocks in code

For renames, a moved block in your .tf files does the same job as state mv, and it goes through code review like any other change. For bringing an existing resource under Terraform, an import block works the same way.

2. Keep State in a Remote Backend

By default, Terraform writes terraform.tfstate next to your code. That is fine for a test on your own machine and risky for anything else: nobody else can see it, and it disappears with the laptop.

A remote backend stores state in a shared place, such as an Amazon S3 bucket, Azure Blob Storage, Google Cloud Storage or HCP Terraform. Everyone on the team, and the pipeline, reads the same copy. Here is an S3 backend:

hcl
terraform {
  backend "s3" {
    bucket       = "my-company-terraform-state"
    key          = "network/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

After you add or change a backend, run init again. Terraform offers to copy any existing local state to the new place.

bash
terraform init -migrate-state

3. Turn On State Locking

If two people run apply at the same moment, both write to the same state file, and one change can overwrite the other. Locking prevents this. While one run holds the lock, any other run waits or stops with a message.

Terraform locks state on its own for every operation that could write to it, as long as the backend supports locking. On the S3 backend, use_lockfile = true (shown above) turns it on. It needs a recent Terraform version, because older versions do not know this setting; check with terraform version. Older setups used a DynamoDB table for the lock; HashiCorp now marks that option as deprecated, so new projects should use the lock file. See the S3 backend documentation.

If a run crashes and leaves a lock behind, Terraform prints the lock ID. Remove the lock only when you are sure nobody else is running Terraform:

bash
terraform force-unlock LOCK_ID

4. Back Up the State File

A remote backend can still lose data: a bad apply, a deleted object, a script that writes garbage. Keep old versions so you can go back.

On S3, turn on bucket versioning. Every write to the state file then keeps the previous copy, and HashiCorp recommends it for state recovery:

bash
aws s3api put-bucket-versioning --bucket my-company-terraform-state --versioning-configuration Status=Enabled

Before a risky change, you can also save a copy of the current state yourself:

bash
terraform state pull > backup.tfstate

Keep backups private

A backup file holds the same secrets as the live state. Store it somewhere encrypted and never commit it to Git.

5. Use One State per Environment

Development, staging and production should never share one state file. With a single state, a mistake in a test change can reach production, and every plan has to look at everything at once.

Give each environment its own folder and its own backend key (or its own bucket), for example:

EnvironmentFolderState key
Developmentenvs/devdev/terraform.tfstate
Stagingenvs/stagingstaging/terraform.tfstate
Productionenvs/prodprod/terraform.tfstate

Shared parts go into modules that every environment calls, so the code is written once. Terraform CLI workspaces can also split state, but HashiCorp says they do not suit environments that need different credentials or access rules, which is usually the case for production.

6. Keep Terraform Code in Git

In a Git repository, every change to your infrastructure code has an author, a date and a reason, and a bad change can be rolled back. Teams can review changes in pull requests before anything reaches the cloud.

Some files must never go into the repository. A .gitignore for Terraform usually includes:

gitignore
.terraform/
*.tfstate
*.tfstate.*
*.tfplan
crash.log

Do commit .terraform.lock.hcl. It pins the provider versions, so everyone and the pipeline use the same ones.

7. Check Every Change in CI

Continuous integration runs the same checks on every pull request, so problems show up before anyone reviews the change. A simple Terraform pipeline runs these three steps.

Check the formatting:

bash
terraform fmt -check -recursive

Check that the configuration is valid:

bash
terraform validate

Show exactly what would change, and save the plan:

bash
terraform plan -out=plan.tfplan

Post the plan output in the pull request, so the reviewer sees what will change in the cloud as well as the code. Free scanners such as TFLint or Checkov can be added later to catch common mistakes and insecure settings.

8. Run Apply Only From the Pipeline

When everyone runs terraform apply from their own laptop, nobody knows which version of the code was applied, with which credentials, or by whom. Move apply into the pipeline and give only the pipeline write access to the cloud.

  1. A pull request runs fmt, validate and plan.

  2. A teammate reviews the code and the plan, then merges.

  3. After the merge, the pipeline runs plan again on the main branch and saves it.

  4. Someone approves that plan, and the pipeline applies it.

bash
terraform apply plan.tfplan

With a saved plan file, Terraform carries out only the actions that were approved. If the plan and apply run in different jobs, pass the plan file between them as a pipeline artifact. Apply it soon after approval: if the state changed in the meantime, Terraform refuses the old plan and you run plan again. Plan files can contain secrets too, which is why *.tfplan is in the .gitignore above. For production, add a manual approval step before this job runs.

Quick Checklist

PracticeWhat goes wrong without it
Terraform commands onlyA hand edit breaks the state file
Remote backendState is lost with a laptop, or each person has a different copy
State lockingTwo runs at once overwrite each other
Backups and versioningNo way back after a bad change
One state per environmentA test change reaches production
Code in GitNo history, no review, no rollback
CI checksErrors are found after deploy
Apply from the pipelineNobody knows who changed what

Key takeaways

  • The state file is the most important file in a Terraform project. Share it, lock it and version it.
  • Never edit state by hand. Use terraform state commands or moved and import blocks.
  • Split environments so a mistake stays small.
  • Let Git, CI and the pipeline handle every change, from pull request to apply.

FAQ

Should I commit the terraform.tfstate file to Git?

No. State can contain secrets in plain text, and Git cannot lock it. Keep it in a remote backend and add *.tfstate to .gitignore.

Do I still need DynamoDB for state locking on S3?

Not for new projects. The S3 backend can lock with a lock file in the same bucket (use_lockfile = true). The DynamoDB option still works but is marked as deprecated.

What should I do if the state is locked and nobody is running Terraform?

Check with your team and your pipeline first. If the lock is really left over from a crashed run, remove it with terraform force-unlock and the lock ID that Terraform shows.

Are Terraform workspaces enough to separate staging and production?

Usually not. Workspaces share one backend and one set of credentials. Separate folders with their own backends give each environment its own access rules.

Learn More

This guide was inspired by the video 8 Terraform Best Practices that will improve your TF workflow immediately. For the official details, read HashiCorp’s pages on remote state and state locking.

Related guides on infotechtu.com

Share this guide

Save

Get new guides by email

One short email when a new guide is out. Unsubscribe at any time.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top