状态管理
远程后端
# S3 后端(带 DynamoDB 锁)
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "production/vpc/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-lock"
}
}
# GCS 后端
terraform {
backend "gcs" {
bucket = "my-terraform-state"
prefix = "terraform/state"
}
}
# Terraform Cloud
terraform {
cloud {
organization = "my-org"
workspaces {
name = "production"
}
}
}
状态命令
# 列出状态中所有资源
terraform state list
# 查看特定资源详情
terraform state show aws_instance.web
# 移动资源(重命名或移入模块)
terraform state mv aws_instance.web aws_instance.app
terraform state mv aws_instance.web module.compute.aws_instance.web
# 从状态中移除资源(不销毁)
terraform state rm aws_instance.legacy
# 强制解锁(锁卡住时)
terraform force-unlock LOCK_ID
导入已有资源
# CLI 导入
terraform import aws_instance.web i-1234567890abcdef0
terraform import aws_s3_bucket.data my-existing-bucket
# Import 块(Terraform >= 1.5,推荐)
import {
to = aws_instance.web
id = "i-1234567890abcdef0"
}
# 生成已有资源的配置
terraform plan -generate-config-out=generated.tf
工作区
# 创建和切换工作区
terraform workspace new staging
terraform workspace select production
# 在配置中使用工作区
resource "aws_s3_bucket" "app" {
bucket = "my-app-${terraform.workspace}"
}
# 注意:复杂多环境配置推荐使用分离的 state 文件
# 而非工作区
敏感值
# 将变量标记为敏感
variable "db_password" {
type = string
sensitive = true
}
# 将输出标记为敏感
output "connection_string" {
value = "postgresql://admin:${var.db_password}@db:5432/app"
sensitive = true
}
# 注意:敏感值仍存储在 tfstate 中
# 请对远程状态加密并限制访问权限