Terraform State 管理
Vibe Prompt
「幫我設定 Terraform 遠端 State 儲存在 S3,並使用 DynamoDB 做 Lock。」
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "prod/terraform.tfstate"
region = "ap-northeast-1"
dynamodb_table = "terraform-state-lock"
encrypt = true
}
}
為什麼需要 State?
Terraform State 記錄了實際雲端資源與設定檔的對應關係。如果 State 遺失,Terraform 就不知道哪些資源是它管理的。
State 最佳實踐
- ✅ 遠端儲存(S3 / GCS / Azure Storage)
- ✅ 啟用 Lock 防止多人同時變更
- ✅ 啟用加密
- ❌ 不要手動編輯 State 檔案
- ❌ 不要將 State 提交到 Git
關鍵要點
- ✅ Terraform = Infrastructure as Code (IaC) 的業界標準
- ✅ HCL (HashiCorp Configuration Language) 宣告式定義基礎設施
- ✅
terraform plan顯示將要做的變更,apply執行變更 - ✅ State File (terraform.tfstate) 是真實世界的來源比對
- ✅ Module 讓基礎設施程式碼可以重用
常用命令
| 命令 | 用途 |
|------|------|
| terraform init | 初始化工作目錄,下載 Provider |
| terraform fmt | 格式化程式碼 |
| terraform validate | 驗證語法正確性 |
| terraform plan | 顯示執行計畫 |
| terraform apply | 執行變更 |
| terraform destroy | 刪除所有資源 |
| terraform state list | 列出 State 中的所有資源 |
遠端 State 儲存比較
| 後端 | 鎖定機制 | 加密 | 適用平台 | |:----:|:--------:|:----:|---------| | S3 + DynamoDB | DynamoDB 鎖定表 | SSE-S3/KMS | AWS | | Azure Storage | Azure 自動處理 | 靜態加密 | Azure | | GCS | Cloud Storage 自動處理 | 預設加密 | GCP | | Terraform Cloud | 自動處理 | 加密 | 多雲 | | Consul | Session 鎖定 | 選配 | 自管 |
# S3 後端範例
terraform {
backend "s3" {
bucket = "company-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-west-2"
encrypt = true
dynamodb_table = "terraform-state-lock"
}
}
Terraform State:基礎設施的資料庫
什麼是 State?
Terraform State 記錄了基礎設施的「當前狀態」——哪些資源被建立、它們的屬性和依賴關係。State 是 Terraform 的核心,沒有 State 就無法知道資源的實際狀況。
State 的作用
| 功能 | 說明 | |:----|:----| | 資源對應 | 將 .tf 檔案中的資源和雲端上的實際資源對應 | | 效能 | 不用每次都去雲端查詢所有資源 | | 依賴關係 | 記錄資源之間的建立順序 | | 差異比對 | 比較 .tf 檔案和實際狀態的差異 |
Remote State
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "production/network.tfstate"
region = "us-west-2"
# 啟用 DynamoDB Lock
dynamodb_table = "terraform-lock"
encrypt = true
}
}
State Locking
多人同時修改基礎設施會造成衝突。DynamoDB 提供 State Lock——一次只能一個人執行 apply,其他人排隊等待。
下一章預告
State 是 Terraform 的核心機制。接下來會教你 Module 封裝和 CI/CD 整合。