Mục lục
- State Management & Team Workflows
State Management & Team Workflows
Đây là câu chuyện kinh hoàng mà mọi infrastructure engineer trải qua ít nhất một lần:
Bạn spin up một database với Terraform. State updates trên laptop của bạn. Bạn đi ăn trưa. Đồng nghiệp Sarah pull latest code, chạy terraform apply với state file lỗi thời của cô ấy. Terraform nghĩ database không tồn tại. Cố gắng recreate nó. Production breaks. Slack của bạn explodes.
Nghe quen không?
Bạn đã conquer Terraform basics, xây dựng reusable modules, và deploy multi-cloud infrastructure. Nhưng có một vấn đề lớn mà chúng ta đang lảng tránh: local state files không scale vượt quá một người.
Làm việc một mình? Local state OK. Thêm developer thứ hai? Bạn đang chơi Russian roulette với infrastructure của mình.
Đây là những gì bạn sắp học:
- Tại sao local state là quả bom hẹn giờ cho teams
- Cách cấu hình remote backends (S3, GCS, Azure Blob)
- State locking thực sự ngăn disasters
- Environment separation không để bạn nuke production nhầm
- Safe state migration không làm đổ bất cứ thứ gì
- Cách recover khi (không phải nếu) state đi sai hướng
Cuối cùng, bạn sẽ có state management production-grade scale từ 2 đến 200 developers.
📦 Code Examples
Repository: terraform-hcl-tutorial-series This Part: Part 9 - State Management
Lấy working example:
git clone https://github.com/khuongdo/terraform-hcl-tutorial-series.git
cd terraform-hcl-tutorial-series
git checkout part-09
cd examples/part-09-state-management/
# Cấu hình remote state backends
terraform init
terraform plan
Vấn Đề Local State: Khi Teams Va Chạm
Hãy phân tích tại sao local state files là time bombs cho infrastructure:
Năm Cách Local State Phá Hủy Teams
1. Không Có Single Source of Truth Mọi developer có state file riêng. Của bạn nói database tồn tại. Của Sarah không. Ai đúng? Ai chạy terraform apply cuối cùng thắng. Spoiler: mọi người thua.
2. Zero Concurrent Access Protection Bạn chạy terraform apply. Sarah chạy terraform apply cùng lúc. Cả hai processes cố modify cùng infrastructure. State file corrupts. Infrastructure vào undefined state. Chúc may mắn recovery.
3. Laptop Của Bạn Không Phải Backup Strategy Đổ coffee lên MacBook? Mất state file? Infrastructure của bạn vẫn tồn tại trên cloud, nhưng Terraform không biết nó đã tạo gì. Bạn không thể modify. Không thể destroy sạch sẽ. Bạn stuck phải manually import hàng trăm resources.
4. Sensitive Data, Zero Encryption State files chứa mọi thứ: database passwords, API keys, private IPs. Ngồi không mã hóa trên laptop. Sẵn sàng cho bất kỳ ai lấy máy mở khóa của bạn ở coffee shop.
5. No Audit Trail Ai thay đổi gì? Khi nào? Tại sao? Không biết. State files không track history. Khi production breaks lúc 2 AM, bạn zero forensics.
Giải pháp? Ngừng lưu state trên laptops. Đặt nó ở nơi team có thể share.
Remote State Backends: One State File to Rule Them All
Remote state backends đơn giản: đặt state file của bạn ở nơi mọi người access được.
Thay vì terraform.tfstate sống trên laptop, nó sống trong S3, Google Cloud Storage, hoặc Azure Blob Storage. Khi bạn chạy terraform apply, nó pulls latest state từ cloud, makes changes, và pushes updated state back.
Cách Nó Hoạt Động (Visual)
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Developer │ │ Developer │ │ CI/CD │
│ You │ │ Sarah │ │ Pipeline │
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
│ │ │
│ terraform apply │ │
└──────────┬──────────┴─────────────────────┘
│
▼
┌─────────────────────┐
│ Remote Backend │
│ (S3 / GCS / Azure) │
│ │
│ terraform.tfstate │
│ (Single source of │
│ truth) │
└─────────────────────┘
Bạn, Sarah, và CI/CD pipeline đều reference cùng state file. Không còn "works on my machine" disasters.
Configuring Remote State: Step-by-Step
Pick backend matching cloud provider. Bạn chỉ cần configure một trong số này.
Option 1: AWS S3 Backend với DynamoDB Locking
S3 stores state file. DynamoDB provides locking nên hai người không thể chạy terraform apply đồng thời.
Step 1: Create Backend Infrastructure
Đây là chicken-and-egg problem: Bạn cần S3 và DynamoDB để store Terraform state, nhưng làm sao create những resources đó bằng Terraform nếu chưa có state storage?
Câu trả lời: Create backend infrastructure manually first (hoặc trong Terraform project riêng với local state). Khi nó tồn tại, migrate main project để sử dụng nó.
# backend-resources.tf (chạy FIRST trong directory riêng)
provider "aws" {
region = "us-west-2"
}
# S3 bucket cho state storage
resource "aws_s3_bucket" "terraform_state" {
bucket = "my-company-terraform-state" # Phải globally unique
lifecycle {
prevent_destroy = true # Safety: không accidentally delete state
}
}
# Enable versioning cho state file recovery
resource "aws_s3_bucket_versioning" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration {
status = "Enabled"
}
}
# Enable server-side encryption
resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
# Block public access (security best practice)
resource "aws_s3_bucket_public_access_block" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
# DynamoDB table cho state locking
resource "aws_dynamodb_table" "terraform_locks" {
name = "terraform-state-locks"
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
attribute {
name = "LockID"
type = "S"
}
}
Deploy một lần (rồi không bao giờ touch lại):
cd backend-setup
terraform init
terraform apply
# Output: S3 bucket và DynamoDB table created
Step 2: Configure Main Project Để Sử Dụng Remote State
Giờ đi tới actual infrastructure project và nói Terraform dùng S3 backend:
# main.tf (main infrastructure project của bạn)
terraform {
backend "s3" {
bucket = "my-company-terraform-state"
key = "prod/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "terraform-state-locks"
encrypt = true
}
}
provider "aws" {
region = "us-west-2"
}
# Infrastructure code của bạn tiếp tục ở đây...
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
}
Migrate từ local sang remote state:
terraform init
# Terraform phát hiện bạn đổi backend
# Prompt: "Do you want to copy existing state to the new backend?"
# Answer: yes
# Local state file của bạn giờ uploaded lên S3
# Delete local state: rm terraform.tfstate*
Done. State của bạn giờ trong S3, accessible cho toàn team.
State Locking: Không Destroy Infrastructure Đồng Thời
State locking ngăn nightmare này:
Cách Locking Hoạt Động
- Bạn chạy
terraform apply - Terraform acquires lock trên state file
- Sarah cố chạy
terraform apply - Cô ấy nhận error: "State locked by user@you. Lock ID: abc123. Cannot proceed."
- Apply của bạn finishes, lock releases
- Sarah chạy apply thành công
Backend support:
- AWS S3: Requires DynamoDB table
- GCS: Built-in, automatic
- Azure Blob: Built-in, automatic
Environment Separation: Không Nuke Production Nhầm
Bạn có ba environments: dev, staging, production. Mỗi cái cần infrastructure riêng. Mỗi cái cần state file riêng.
Approach 2: Directory-Based Separation (Production Standard)
Directories riêng cho mỗi environment. Physically impossible accidentally deploy sai.
infrastructure/
├── modules/web-server/
├── environments/
│ ├── dev/main.tf
│ ├── staging/main.tf
│ └── prod/main.tf
Usage:
cd environments/prod
terraform apply # Chỉ affects production
cd environments/dev
terraform destroy # Chỉ affects dev (impossible hit prod nhầm)
Tại sao safer: Bạn không thể accidentally deploy production khi ở dev directory. File system protects bạn.
Checkpoint: Can You Answer These?
Trước Part 10, đảm bảo bạn hiểu:
1. Tại sao local state fails cho teams?
Không single source of truth, zero concurrent access protection, không disaster recovery, sensitive data stored unencrypted, không audit trail.
2. Ba production-grade remote backends là gì?
AWS S3 (với DynamoDB cho locking), Google Cloud Storage (built-in locking), Azure Blob Storage (built-in locking).
3. State locking ngăn gì?
Ngăn hai người (hoặc CI/CD jobs) chạy terraform apply cùng lúc. Không có locking, simultaneous applies corrupt state file.
4. Workspaces vs directory separation: Nên dùng cái nào cho production?
Directory-based separation. Workspaces tiện nhưng dễ nhầm environment. Separate directories makes physically impossible mix up dev và prod.
5. Migrate từ local state sang remote state mà không break infrastructure?
Update backend config trong main.tf, chạy terraform init, answer "yes" khi prompted copy state, verify với terraform plan, delete local state files.
Series navigation:
- Part 8: Multi-Cloud Patterns
- Part 9: State Management & Team Workflows (Bạn đang ở đây)
- Part 10: Testing & Validation
Phần này là part của series "Terraform from Fundamentals to Production". Bạn 9/12 đường tới mastering Infrastructure as Code.