Terraform State Management

๐Ÿ”ฅ Vibe Prompt

"Configure Terraform remote state in S3 with DynamoDB for state locking."

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-1"
    dynamodb_table = "terraform-state-lock"
    encrypt        = true
  }
}

Why Remote State?

Terraform state maps real cloud resources to your config. Losing state means Terraform doesn't know what it manages.

Best Practices

  • โœ… Remote storage (S3/GCS/Azure)
  • โœ… Enable locking (DynamoDB)
  • โœ… Enable encryption
  • โŒ Don't edit state manually
  • โŒ Don't commit state to Git

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

  • Official documentation
  • Open source projects on GitHub
  • Community forums and discussions
  • Related courses and tutorials

Local State

By default, Terraform stores state in a local terraform.tfstate file.

Local State Pitfalls

| Issue | Problem | Solution | |-------|---------|----------| | No sharing | Only one person can run Terraform safely | Use remote state | | No locking | Two people can corrupt state simultaneously | Add DynamoDB lock | | No backup | Lost file = lost infrastructure tracking | Remote backup | | Secrets in state | Passwords, keys stored in plain text | Encrypt state file |

Remote State with S3

# backend.tf
terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "production/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-state-lock"
  }
}

Bucket Creation

# Create S3 bucket for state files
aws s3api create-bucket \
  --bucket my-terraform-state-bucket-2024 \
  --region us-east-1

# Enable versioning (safety net)
aws s3api put-bucket-versioning \
  --bucket my-terraform-state-bucket-2024 \
  --versioning-configuration Status=Enabled

# Create DynamoDB table for state locking
aws dynamodb create-table \
  --table-name terraform-state-lock \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

State Commands

# List resources in state
terraform state list

# Show details of a specific resource
terraform state show aws_instance.web

# Move resource to new address
terraform state mv \
  aws_instance.web \
  aws_instance.web_v2

# Remove resource from state (not destroy)
terraform state rm aws_instance.old

# Import existing resource into state
terraform import aws_instance.web i-1234567890abcdef0

# Pull state to local file
terraform state pull > backup.tfstate

# Push local state to backend
terraform state push backup.tfstate

State File Contents

The state file is a JSON document mapping resources to real-world infrastructure.

{
  "version": 4,
  "terraform_version": "1.5.0",
  "serial": 12,
  "lineage": "abc-123-def",
  "outputs": {},
  "resources": [
    {
      "module": "",
      "mode": "managed",
      "type": "aws_instance",
      "name": "web",
      "provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
      "instances": [
        {
          "attributes": {
            "id": "i-1234567890abcdef0",
            "instance_type": "t2.micro",
            "ami": "ami-0c55b159cbfafe1f0",
            "public_ip": "54.123.45.67",
            "tags": {"Name": "WebServer"}
          },
          "sensitive_attributes": [],
          "private": "base64-encoded-sensitive-data"
        }
      ]
    }
  ]
}

State Locking

DynamoDB prevents concurrent runs from corrupting state.

# Force unlock (use cautiously!)
terraform force-unlock LOCK_ID

# Check if state is locked
aws dynamodb get-item \
  --table-name terraform-state-lock \
  --key '{"LockID": {"S": "my-terraform-state-bucket/production/terraform.tfstate"}}'

Workspaces

Workspaces create separate state files for different environments.

terraform workspace list         # See all workspaces
terraform workspace new staging  # Create staging workspace
terraform workspace select prod  # Switch to production
terraform workspace show         # Show current workspace
# Environment-specific values from workspace name
locals {
  environment = terraform.workspace
  instance_count = {
    development = 1
    staging     = 2
    production  = 5
  }[terraform.workspace]
}

Summary

Terraform state tracks your real-world infrastructure. Remote state with S3 and DynamoDB enables team collaboration with locking and versioning.

Key takeaways:

  • State maps Terraform config to real infrastructure |
  • Local state: simple but no sharing, locking, or backup |
  • Remote state (S3): shared, versioned, encrypted |
  • DynamoDB locking prevents concurrent state corruption |
  • terraform state list/show/mv/rm manage state |
  • terraform import brings existing resources under management |
  • Workspaces create isolated state per environment |
  • State files contain sensitive data โ€” always encrypt |

What's Next: Terraform Modules

The next chapter covers reusable Terraform modules.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!