# Remote State, Locking and Workspaces — Terraform

Source: https://www.skillbyai.com/en/terraform/s-remote

> State for teams.

## Shared, locked, encrypted

Local state files do not work for teams: people overwrite each other's changes and secrets sit on laptops. Use a **remote backend** (an S3 bucket with locking, Azure Blob, Google Cloud Storage, HCP Terraform, and others) that stores state centrally, **locks** it during operations so two applies cannot run at once, keeps versions, and encrypts at rest. Restrict access to the state. Separate environments with separate state (directories or workspaces) so a dev mistake cannot touch prod.

## An S3 backend with locking (sketch)

Not run here; it needs a cloud account or a remote backend. Check backend options for your Terraform version.

```hcl
terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "shop/prod/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true      # S3-native state locking
  }
}
```

## One state per environment

Use separate state files (and ideally accounts) for dev, staging and prod to limit the blast radius.

**Quiz:** Why does remote state need locking?

- [ ] To make plans faster
- [x] To stop two people or pipelines applying changes at the same time
- [ ] To hide outputs
- [ ] Locking deletes old versions

*Answer:* To stop two people or pipelines applying changes at the same time. Concurrent applies corrupt state.
