Quản lý State
Hiểu về state files, backend S3, auto-import, và xử lý drift
State Files
Terraform lưu trạng thái của infrastructure trong state files:
Shared vs Stage State
| Shared | Stage | |
|---|---|---|
| State file | shared/terraform.tfstate | terraform.tfstate |
| Scope | Global / account-level | Per-region |
| Khi destroy stage | Không bị ảnh hưởng | Xoá hết |
Cảnh báo
Không commit terraform.tfstate vào git! File này chứa sensitive data. Sử dụng .gitignore để exclude.
Auto Import
deploy.ps1 tự dò và import 31 loại resource đã tồn tại trên AWS:
| Loại Resource | Ví dụ |
|---|---|
| ECR Repository | milu2/milu2-stage-api, milu2/milu2-stage-web, ... |
| ALB / NLB | MILU2-stage-alb, MILU2-stage-nlb |
| Target Group | MILU2-stage-api-tg, MILU2-stage-web-tg, ... |
| ASG | MILU2-stage-api-atg |
| Launch Template | MILU2-stage-api-template |
| CloudWatch Alarms | MILU2-stage-*-alarm |
Auto Import Logic
# Auto import flow in deploy.ps1:
# 1. Check if resource exists on AWS (aws ecr describe-repositories, etc.)
# 2. Check if resource is in state (terraform state list)
# 3. If exists on AWS but not in state → terraform import
# 4. Continue with terraform plan/applyImport thủ công
Khi cần import một resource cụ thể:
Manual Import Examples
# Import ECR repository
terraform import 'module.ecr.aws_ecr_repository.this["milu2/milu2-stage-api"]' milu2/milu2-stage-api
# Import ALB
terraform import 'module.alb.aws_lb.internal' arn:aws:elasticloadbalancing:ap-southeast-1:123456789012:loadbalancer/app/MILU2-stage-alb/abc123
# Import Target Group
terraform import 'module.target_groups_listeners.aws_lb_target_group.api' arn:aws:elasticloadbalancing:...:targetgroup/MILU2-stage-api-tg/xyz789
# View current state
terraform state list
# Show specific resource in state
terraform state show 'module.vpc.aws_vpc.this'Xử lý Drift
Drift xảy ra khi AWS thực tế khác với state (do thay đổi manual trên Console):
Drift Detection
# Detect drift
terraform plan
# Output shows differences between state and actual AWS
# Refresh state to match AWS (accept manual changes)
terraform apply -refresh-only
# Or revert AWS to match state (overwrite manual changes)
terraform applyThông tin
Tip: Chạy terraform plan thường xuyên để phát hiện drift sớm. Nếu có thay đổi manual, quyết định: refresh state (chấp nhận thay đổi) hoặc apply (ghi đè về code).
Các lệnh State hữu ích
State Commands
# List all resources in state
terraform state list
# Show details of a specific resource
terraform state show 'module.vpc.aws_vpc.this'
# Remove a resource from state (without destroying it)
terraform state rm 'module.ec2_instances.aws_instance.this["mysql-1"]'
# Move/rename a resource in state
terraform state mv 'module.old.aws_instance.this' 'module.new.aws_instance.this'
# Pull remote state to local
terraform state pull > backup.tfstate
# Force unlock state (use with caution!)
terraform force-unlock <LOCK_ID>