Terraform State Management Policy
A policy for managing Terraform state files: backend configuration, locking, isolation, access control, versioning, enforcement, and disaster recovery.
Overview
Terraform state is the only record that maps your code to the infrastructure it manages. When a team loses it — or lets two people write it at once — the result is drift, duplicated resources, or leaked secrets. A state management policy turns “how we handle state” from tribal knowledge into written rules: where state lives, who can touch it, how it’s locked and backed up, and what happens when something goes wrong. Use this template as a starting point and adapt the tables and thresholds to your organization.
When to Use
- Setting up Terraform for a new project or team
- Migrating from local state to a remote backend
- Establishing IaC governance when three or more teams share the same state backend
- Preparing for compliance audits (SOC 2, ISO 27001)
- Defining disaster recovery procedures for infrastructure
- Writing the “how we run Terraform” section of an engineering handbook
For the hands-on backend setup that this policy governs, see Store Terraform Remote State in S3 with Locking.
Solution
# Terraform State Management Policy — <Organization Name>
## Policy Overview
| Field | Value |
|-------|-------|
| Organization | Example Corp |
| Policy Version | 1.1 |
| Last Updated | 2026-11-28 |
| Policy Owner | DevOps Team |
| Approved By | Head of Infrastructure |
| Review Cycle | Quarterly |
| Terraform Version | 1.10+ |
| Backend | S3 with native locking (AWS) |
| State Encryption | AES-256 (S3 server-side) |
## 1. Backend Configuration
### Required Backend: S3 with Native Locking
| Component | Purpose | Configuration |
|-----------|---------|---------------|
| S3 bucket | State file storage | Encrypted, versioned, private |
| `.tflock` object | State locking | Native `use_lockfile`, no DynamoDB |
| KMS key | Encryption key | Customer-managed, rotated annually |
| IAM policy | Access control | Least privilege per environment |
Since Terraform 1.10 the [S3 backend](https://developer.hashicorp.com/terraform/language/backend/s3)
locks state natively by writing a `.tflock` object next to the state object.
DynamoDB locking (`dynamodb_table`) is deprecated — see Section 8, Legacy Migrations.
### Backend Configuration Template
```hcl
terraform {
required_version = ">= 1.10.0"
backend "s3" {
bucket = "example-tfstate-prod"
key = "infrastructure/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
kms_key_id = "alias/terraform-state-key"
}
}
```
### Backend Naming Convention
| Environment | S3 Bucket | State Key |
|-------------|-----------|-----------|
| Production | example-tfstate-prod | `<project>/terraform.tfstate` |
| Staging | example-tfstate-staging | `<project>/terraform.tfstate` |
| Development | example-tfstate-dev | `<project>/terraform.tfstate` |
| Shared | example-tfstate-shared | `<project>/terraform.tfstate` |
### S3 Bucket Configuration
| Setting | Value | Rationale |
|---------|-------|-----------|
| Versioning | Enabled | Recover from accidental overwrites |
| Encryption | AES-256 (SSE-S3) or AWS KMS (SSE-KMS) | Protect state contents |
| Public access block | All enabled | Prevent public exposure |
| Bucket policy | Deny non-SSL requests | Encrypt in transit |
| Lifecycle | Transition to Glacier after 90 days | Cost optimization for old versions |
| MFA delete | Enabled (production) | Prevent accidental deletion |
| Access logging | Enabled | Audit access to state |
## 2. State Isolation
### Isolation Strategy
| Level | Isolation Method | Rationale |
|-------|-----------------|-----------|
| Environment | Separate S3 buckets | Prod and dev never share state |
| Project | Separate state keys | Projects don't depend on each other |
| Team | Separate AWS accounts | Full isolation for compliance |
| Region | Separate state per region | Regional infrastructure isolation |
### Workspace Policy
| Rule | Enforcement |
|------|-------------|
| No Terraform workspaces for environment isolation | Use separate state files |
| Workspaces allowed for parallel development | Within same environment only |
| Default workspace must not be used for production | Named workspaces only |
### State File Structure
```
example-tfstate-prod/
├── networking/
│ └── terraform.tfstate
├── database/
│ └── terraform.tfstate
├── application/
│ └── terraform.tfstate
├── monitoring/
│ └── terraform.tfstate
└── security/
└── terraform.tfstate
```
## 3. Access Control
### IAM Policy: Read-Only (Plan)
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::example-tfstate-prod",
"arn:aws:s3:::example-tfstate-prod/*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::example-tfstate-prod/*.tflock"
]
}
]
}
```
With native locking, the lock is an S3 object (`<key>.tflock`), so locking
permissions are S3 permissions scoped to the `*.tflock` suffix — no DynamoDB
permissions are needed. The read-only role still allows acquiring and
releasing locks because `plan` also locks state.
### IAM Policy: Read-Write (Apply)
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::example-tfstate-prod",
"arn:aws:s3:::example-tfstate-prod/*"
]
}
]
}
```
### Access Matrix
| Role | Plan (Read) | Apply (Write) | State Pull | State Push | Lock/Unlock |
|------|-------------|---------------|------------|------------|-------------|
| Developer | ✅ (dev/staging) | ❌ | ✅ (dev/staging) | ❌ | ✅ (dev/staging) |
| Senior Developer | ✅ (all) | ✅ (dev/staging) | ✅ (all) | ❌ | ✅ (dev/staging) |
| DevOps Engineer | ✅ (all) | ✅ (all) | ✅ (all) | ✅ (dev/staging) | ✅ (all) |
| CI/CD Service Account | ✅ (all) | ✅ (all) | ✅ (all) | ✅ (all) | ✅ (all) |
| Auditor | ✅ (read-only) | ❌ | ✅ (read-only) | ❌ | ❌ |
## 4. State Operations
### Allowed Operations
| Operation | Command | Who | When |
|-----------|---------|-----|------|
| Plan | `terraform plan` | Developers, CI | Before apply |
| Apply | `terraform apply` | CI/CD, DevOps | After plan approval |
| State list | `terraform state list` | Developers, CI | Debugging |
| State show | `terraform state show <resource>` | Developers, CI | Debugging |
| State pull | `terraform state pull` | DevOps, CI | Debugging, backup |
| State push | `terraform state push` | DevOps only | Emergency recovery |
| State mv | `terraform state mv` | DevOps only | Resource renaming |
| State rm | `terraform state rm` | DevOps only | Remove deleted resources |
| Force unlock | `terraform force-unlock` | DevOps only | Stuck locks |
### Prohibited Operations
| Operation | Reason | Alternative |
|-----------|--------|-------------|
| Local state | No locking, no encryption | Remote backend |
| Manual state editing | Corrupts state | Use `terraform state` commands |
| State sharing between environments | Cross-environment dependencies | Separate state files |
| `terraform apply` without plan | No review of changes | Always run plan first |
| `terraform force-unlock` without investigation | Concurrent modifications | Investigate lock owner first |
### State Migration Procedure
```bash
# 1. Back up current state
terraform state pull > backup.tfstate
# 2. Disable old backend
terraform init -backend=false
# 3. Configure new backend in terraform.tf
# (update backend block)
# 4. Initialize with new backend
terraform init -migrate-state
# 5. Verify state
terraform state list
terraform plan # Should show no changes
# 6. Clean up old state
# (remove old S3 objects after verification)
```
## 5. State Security
### Sensitive Data in State
| Data Type | Stored in State? | Mitigation |
|-----------|-----------------|------------|
| Resource IDs | Yes | Not sensitive |
| Resource attributes | Yes | Some may be sensitive |
| Passwords/secrets | Yes (if not using sensitive flag) | Mark as sensitive, use vault |
| Private keys | Yes (if created by Terraform) | Use vault, not Terraform |
| TLS certificates | Yes (if created by Terraform) | Use ACM, not Terraform |
### Marking Resources as Sensitive
```hcl
resource "aws_db_instance" "main" {
username = "admin"
password = var.db_password
# Mark variable as sensitive
}
variable "db_password" {
type = string
sensitive = true
}
# Sensitive values are hidden in plan output
# but still stored in the state file
```
### State File Access Audit
| Log Source | What to Log | Retention |
|------------|-------------|-----------|
| S3 access logs | GetObject, PutObject on state bucket | 1 year |
| CloudTrail | All API calls to the state bucket | 1 year |
| Terraform logs | Plan and apply operations | 90 days |
| CI/CD logs | Who triggered apply and when | 1 year |
## 6. Disaster Recovery
### Backup Strategy
| Component | Backup Method | Frequency | Retention |
|-----------|--------------|-----------|-----------|
| State file | S3 versioning | Every apply | All versions retained |
| State file | Manual export | Weekly | 90 days |
| Lockfile | None required | — | `.tflock` objects are ephemeral |
| Backend config | Git repository | Every commit | Per Git history |
### Recovery Procedures
#### Recover from Accidental State Deletion
```bash
# 1. List previous versions
aws s3api list-object-versions \
--bucket example-tfstate-prod \
--prefix infrastructure/terraform.tfstate
# 2. Restore previous version
aws s3api copy-object \
--copy-source example-tfstate-prod/infrastructure/terraform.tfstate?versionId=<version-id> \
--bucket example-tfstate-prod \
--key infrastructure/terraform.tfstate
# 3. Verify state
terraform state list
terraform plan # Should show no changes
```
#### Recover from Corrupted State
```bash
# 1. Pull current state
terraform state pull > corrupted.tfstate
# 2. Restore from S3 version
aws s3api copy-object \
--copy-source example-tfstate-prod/infrastructure/terraform.tfstate?versionId=<version-id> \
--bucket example-tfstate-prod \
--key infrastructure/terraform.tfstate
# 3. Import missing resources
terraform import aws_instance.web i-1234567890abcdef0
# 4. Verify
terraform plan
```
#### Recover from Stuck Lock
```bash
# 1. Verify no other Terraform process is running
# (check CI/CD pipelines, developer terminals)
# 2. Release the stale lock
terraform force-unlock <lock-id>
# 3. Re-run plan
terraform plan
```
## 7. CI/CD Integration
### Pipeline State Operations
| Stage | State Operation | Permissions | Duration |
|-------|----------------|-------------|----------|
| Init | `terraform init` | Read backend config | 30 sec |
| Plan | `terraform plan` | Read state, acquire lock | 2-5 min |
| Apply | `terraform apply` | Read/write state, lock | 5-15 min |
| Destroy | `terraform destroy` | Read/write state, lock | 5-15 min |
### CI/CD Best Practices
| Practice | Implementation | Rationale |
|----------|----------------|-----------|
| Use service accounts | IAM role for CI, not user credentials | Auditable, revocable |
| Plan in PR pipeline | `terraform plan` on every PR | Review changes before merge |
| Apply on merge | `terraform apply` after merge to main | Automated deployment |
| No manual apply | All applies through CI/CD | Consistent, auditable |
| Plan output as PR comment | Bot posts plan summary | Review without terminal |
| State lock timeout | 10 min in CI config | Prevent stuck pipelines |
## 8. Legacy Migrations
### DynamoDB Locking (Terraform < 1.10)
| Step | Action |
|------|--------|
| 1 | Remove `dynamodb_table` from the backend block |
| 2 | Set `use_lockfile = true` |
| 3 | Run `terraform init -reconfigure` per workspace |
| 4 | Keep the DynamoDB table until every workspace migrated |
| 5 | Delete the table and its IAM permissions |
Local-state projects follow the same pattern: add the backend block and run
`terraform init -migrate-state`.
## 9. Enforcement and Exceptions
### Enforcement
| Rule | Mechanism |
|------|-----------|
| No local state | CI pipelines fail if no backend block exists |
| Backend config required | `terraform init` runs before any plan in CI |
| Production applies only via CI | IAM denies write access to user roles |
| Lock acquisition logged | CloudTrail alarms on repeated lock errors |
### Exceptions
| Exception | Approval | Expiry |
|-----------|----------|--------|
| Sandbox/personal projects may use local state | Team lead | 90 days |
| Legacy DynamoDB locking during migration | Policy owner | Until migration completes |
| Non-AWS backends (Azure Blob, GCS) | Policy owner | Reviewed quarterly |
Exceptions must be recorded in this document with an owner and an expiry date.
Expired exceptions are violations.
## 10. Metrics and Review
### Policy Health Metrics
| Metric | Target | Source |
|--------|--------|--------|
| Applies through CI/CD | 100% | CI/CD logs |
| Stale locks per month | 0-2 | CloudTrail / lock errors |
| State files without versioning | 0 | Bucket audit |
| Public state objects | 0 | AWS Config / access analyzer |
| Exceptions past expiry | 0 | This document |
### Quarterly Review Agenda
1. Review exception register — renew or close expired entries
2. Audit state bucket configurations against Section 1
3. Review access matrix changes and IAM diffs
4. Check backup/restore drill results (run one restore per quarter)
5. Update Terraform version floor if `required_version` moved
A ready-to-fill version of this policy plus the backend and IAM files lives in the companion repository.
Explanation
Terraform state tracks the mapping between configuration and real infrastructure — resource IDs, attributes, and whatever values Terraform read or generated. It’s also where secrets can end up: anything a resource stores (passwords, keys, connection strings) lands in the state file unless you design around it. That’s why this policy treats the state bucket like a database, not a scratch file: encrypted, versioned, access-controlled, and audited.
The backend choice is where most policies age badly. DynamoDB locking was the standard for years, so older docs and blog posts still prescribe it — but since Terraform 1.10 the S3 backend writes the lock as an S3 object itself. Dropping dynamodb_table removes a table to provision, a second service to grant permissions on, and one item off the AWS bill. If your organization still runs the DynamoDB setup, Section 8 covers the migration path; it’s a config change plus terraform init -reconfigure, not a state migration.
State isolation prevents cross-environment dependencies. Production and development must have separate state files, ideally in separate S3 buckets — a change in dev should never be able to break prod, and “separate keys in one bucket” only protects you until someone grants broad access to that bucket. Separate buckets also make blast radius auditable: you can point at a bucket and say “everything in here is production.”
Access control splits readers from writers. Developers need s3:GetObject for terraform plan but shouldn’t hold PutObject on production state — that’s the difference between “can see it” and “can break it”. The IAM examples scope write access to the CI service account and senior DevOps, which is what makes “no manual apply” enforceable rather than aspirational.
Disaster recovery leans almost entirely on S3 versioning: every apply writes a new object version, so a bad state is a copy-object away from the previous good one. The manual weekly export exists because versioning doesn’t help if the bucket itself is compromised — it’s cheap insurance, not a second strategy. Lockfiles need no backup at all; they’re transient by design.
CI/CD integration is what turns the policy from a document into a control. plan on every PR gives reviewers the diff before it lands; apply on merge to main means the write path runs in one place, with one identity, under one log. If your team runs Terraform locally for applies, this is the section that changes behavior.
Finally, treat the policy itself as code: exceptions have owners and expiry dates, metrics have targets, and the quarterly review has a fixed agenda. A policy nobody reviews is worse than no policy — it documents rules nobody follows.
Variants
| Context | Approach | Notes |
|---|---|---|
| Multi-cloud | Use HCP Terraform or Spacelift | Managed backend, no S3 to operate |
| Azure | Use Azure Storage backend | Blob container with lease locking |
| GCP | Use GCS backend | Bucket with object versioning |
| Self-hosted | Use Consul or PostgreSQL backend | For air-gapped environments |
| Large-scale | Use HCP Terraform workspaces | Team-based access, RBAC, run history |
| Compliance | Add KMS encryption + CloudTrail | SOC 2, HIPAA requirements |
| Legacy AWS | S3 + dynamodb_table | Deprecated path — migrate per Section 8 |
What Works
- Use remote state from day one — migrating local state is painful
- Enable S3 versioning — it’s the simplest recovery mechanism
- Turn on
use_lockfile— native locking needs no extra infrastructure - Isolate state per environment — never share prod and dev state
- Mark sensitive variables — hide secrets in plan output
- Automate through CI/CD — no manual terraform apply
- Audit state access — know who changed infrastructure and when
- Give exceptions an owner and an expiry — or they become permanent
Common Mistakes
- Local state in Git — no locking, secrets in version control
- Provisioning DynamoDB for new setups — deprecated since Terraform 1.10
- Shared state across environments — dev changes break prod
- No state versioning — can’t recover from accidental deletion
- Secrets in state without sensitive flag — visible in plan output
- Manual terraform apply — inconsistent, not auditable
- No backup strategy — state loss means infrastructure drift
- Policies without review dates — they fossilize and get ignored
Frequently Asked Questions
Why not use Terraform workspaces for environment isolation?
Workspaces share the same backend configuration and bucket. The backend namespaces each workspace's state under env:/, but access control happens at bucket level — anyone who can write to the bucket can touch every workspace's state. Use separate state files (different S3 keys or buckets) for real isolation. Workspaces are fine for parallel development within the same environment.
Do I still need DynamoDB for state locking?
No. Terraform 1.10 added native locking to the S3 backend: set use_lockfile = true and the backend manages a .tflock object alongside the state. dynamodb_table is deprecated — migrate by removing the argument and running terraform init -reconfigure, then delete the table once every workspace has switched.
How do we handle state when splitting a monolithic Terraform project?
Use terraform state mv to move resources between states. Create the new state file with its own backend configuration, move resources from the old state, and verify both with terraform plan (should show no changes). Remove the resources from the old configuration last. The process is reversible until you delete the old state.
What should we do if terraform state is locked?
First, check whether another Terraform process is actually running — a CI job or a teammate's apply. If yes, wait. If the run crashed without releasing the lock, use terraform force-unlock <lock-id>. Never force-unlock without checking: if a run holds the lock, forcing it lets two processes write state concurrently, which is how state gets corrupted.
How do we migrate state between backends?
Add the new backend block and run terraform init -migrate-state — Terraform pulls the state from the old backend and pushes it to the new one. Verify with terraform plan (should show no changes), update CI/CD, then clean up the old backend.
Should we store Terraform state in Git?
No. State files contain sensitive data, change on every apply, and Git offers no locking — two commits can diverge in ways terraform apply can't reconcile. Store configuration (.tf files) in Git and state in a remote backend. The complete Terraform production guide covers the operational side in more depth.
Related Resources
Store Terraform Remote State in S3 with Locking
How to configure Terraform remote state on S3 with native locking, encryption, and versioning — plus state isolation, workspaces, CI/CD, and DynamoDB migration.
GuideComplete Guide to Terraform in Production
Operate Terraform safely in production: remote state with native locking, environment isolation, drift detection, CI/CD pipelines that apply reviewed plans, and policy as code.
DocTerraform Module Versioning Policy Template
A ready-to-adapt policy for versioning and publishing Terraform modules: semver rules, breaking-change and deprecation workflows, changelog format, registry publishing, and CI/CD release pipelines.
DocInfrastructure as Code Review Template
A template for reviewing Terraform and CloudFormation infrastructure code.
DocCI/CD Pipeline Design Template
A template for documenting CI/CD pipeline stages, gates, environments, deployment strategies, rollback procedures, and security scanning.