Terraform 状态管理最佳实践:远程后端与状态锁
Lisa Tan | 2026-08-26T23:01:40 | DevOps, Cloud
深入讲解 Terraform state 的远程存储、状态锁定、workspace 隔离和 state 拆分策略。
# Terraform 状态管理最佳实践 ## 为什么状态管理重要? Terraform 通过 state 文件跟踪基础设施资源。如果多人同时修改同一份 state,会导致资源冲突甚至误删。 ## 一、远程后端(S3 + DynamoDB) ```hcl terraform { backend "s3" { bucket = "my-terraform-state" key = "prod/network/terraform.tfstate" region = "ap-southeast-1" encrypt = true dynamodb_table = "terraform-locks" } } ``` DynamoDB 提供状态锁:当有人执行 `terraform apply` 时,其他人会收到锁定提示。 ## 二、Workspace 隔离 ```bash # 创建不同环境的 workspace terraform workspace new staging terraform workspace new production # 在代码中引用 resource "aws_instance" "web" { instance_type = terraform.workspace == "production" ? "m5.xlarge" : "t3.micro" tags = { Environment = terraform.workspace } } ``` 每个 workspace 有独立的 state 文件。 ## 三、State 拆分策略 大型项目应将基础设施拆分为多个独立的 state: ``` infra/ network/ # VPC, Subnets, NAT Gateway database/ # RDS, ElastiCache kubernetes/ # EKS Cluster applications/ # K8s Deployments ``` 跨 state 引用使用 `data.terraform_remote_state`: ```hcl data "terraform_remote_state" "network" { backend = "s3" config = { bucket = "my-terraform-state" key = "prod/network/terraform.tfstate" region = "ap-southeast-1" } } resource "aws_instance" "web" { subnet_id = data.terraform_remote_state.network.outputs.public_subnet_id } ``` ## 四、敏感数据保护 ```hcl # 标记敏感输出 output "db_password" { value = random_password.db.result sensitive = true } ``` state 文件中包含明文密码!务必开启 S3 服务端加密,并限制 bucket 访问权限。 ## 五、State 操作命令 ```bash # 查看当前 state terraform state list # 移除资源(不删除真实资源) terraform state rm aws_instance.old_server # 导入已有资源 terraform import aws_s3_bucket.my_bucket my-bucket-name ```