[ PROMPT_NODE_24366 ]
Terraform 设计模式
[ SKILL_DOCUMENTATION ]
# Terraform 模式与用例
架构模式、多环境设置及实际用例。
## 推荐目录结构
terraform/
├── environments/
│ ├── production/
│ │ ├── main.tf
│ │ └── terraform.tfvars
│ └── staging/
│ ├── main.tf
│ └── terraform.tfvars
├── modules/
│ ├── zone/
│ ├── worker/
│ └── dns/
└── shared/ # 各环境共享资源
└── main.tf
**注意:** 由于 v5 版本自动生成的复杂性,Cloudflare 建议避免为 Provider 资源使用模块。建议优先使用环境目录 + 共享状态。
## 多环境设置
hcl
# 目录: environments/{production,staging}/main.tf + modules/{zone,worker,pages}
module "zone" {
source = "../../modules/zone"; account_id = var.account_id; zone_name = "example.com"; environment = "production"
}
module "api_worker" {
source = "../../modules/worker"; account_id = var.account_id; zone_id = module.zone.zone_id
name = "api-worker-prod"; script = file("../../workers/api.js"); environment = "production"
}
## R2 状态后端
hcl
terraform {
backend "s3" {
bucket = "terraform-state"
key = "cloudflare.tfstate"
region = "auto"
endpoints = { s3 = "https://.r2.cloudflarestorage.com" }
skip_credentials_validation = true
skip_region_validation = true
skip_requesting_account_id = true
skip_metadata_api_check = true
skip_s3_checksum = true
}
}
## 包含所有绑定的 Worker
hcl
locals { worker_name = "full-stack-worker" }
resource "cloudflare_workers_kv_namespace" "app" { account_id = var.account_id; title = "${local.worker_name}-kv" }
resource "cloudflare_r2_bucket" "app" { account_id = var.account_id; name = "${local.worker_name}-bucket" }
resource "cloudflare_d1_database" "app" { account_id = var.account_id; name = "${local.worker_name}-db" }
resource "cloudflare_worker_script" "app" {
account_id = var.account_id; name = local.worker_name; content = file("worker.js"); module = true
compatibility_date = "2025-01-01"
kv_namespace_binding { name = "KV"; namespace_id = cloudflare_workers_kv_namespace.app.id }
r2_bucket_binding { name = "BUCKET"; bucket_name = cloudflare_r2_bucket.app.name }
d1_database_binding { name = "DB"; database_id = cloudflare_d1_database.app.id }
secret_text_binding { name = "API_KEY"; text = var.api_key }
}
## Wrangler 集成
**关键:** Wrangler 和 Terraform 不得管理相同的资源。