8. 使用 Terraform 将数据同步到 S3 存储桶
发布: (2026年2月7日 GMT+8 13:58)
3 分钟阅读
原文: Dev.to
Source: Dev.to

实验信息
作为数据迁移项目的一部分,团队必须:
- 创建一个名为 devops-sync-31997 的新私有 S3 存储桶,并在变量
KKE_BUCKET中存储该存储桶名称。 - 将所有数据从现有存储桶 devops-s3-17362 迁移到新存储桶。
- 在迁移后验证两个存储桶中的数据是否完全相同。
所有操作均应使用 Terraform 完成,更新现有的 main.tf(不创建单独的资源文件)。所需文件如下:
variables.tf– 定义KKE_BUCKET。outputs.tf– 输出新存储桶的名称和 ACL。
实验解答
1️⃣ variables.tf
variable "KKE_BUCKET" {
type = string
}
2️⃣ terraform.tfvars
KKE_BUCKET = "devops-sync-31997"
3️⃣ 更新 main.tf(在现有代码后追加)
# Existing bucket (source)
resource "aws_s3_bucket" "wordpress_bucket" {
bucket = "devops-s3-17362"
}
resource "aws_s3_bucket_acl" "wordpress_bucket_acl" {
bucket = aws_s3_bucket.wordpress_bucket.id
acl = "private"
}
# New private bucket (destination)
resource "aws_s3_bucket" "sync_bucket" {
bucket = var.KKE_BUCKET
}
resource "aws_s3_bucket_acl" "sync_bucket_acl" {
bucket = aws_s3_bucket.sync_bucket.id
acl = "private"
}
# Data migration using the AWS CLI
resource "null_resource" "s3_sync" {
provisioner "local-exec" {
command = "aws s3 sync s3://devops-s3-17362 s3://${var.KKE_BUCKET}"
}
depends_on = [
aws_s3_bucket.sync_bucket
]
}
4️⃣ outputs.tf
output "new_kke_bucket_name" {
value = aws_s3_bucket.sync_bucket.bucket
}
output "new_kke_bucket_acl" {
value = aws_s3_bucket_acl.sync_bucket_acl.acl
}
5️⃣ 应用配置
terraform init
terraform validate
terraform apply # 当提示时输入 "yes"

简要说明
| 需求 | 解决方案如何满足 |
|---|---|
使用 variables.tf 创建新的私有 S3 存储桶 | 存储桶名称取自 var.KKE_BUCKET,ACL 设置为 private。 |
| 将所有数据从现有存储桶迁移 | aws s3 sync 在保留文件夹结构的同时复制每个对象。 |
| 确保数据一致性 | 同步操作可以安全地重新运行,源和目标将保持一致。 |
| 全部使用 Terraform | Terraform 创建新存储桶、设置 ACL,并通过 null_resource 触发迁移。 |
不为资源创建单独的 .tf 文件 | 所有资源均添加到已有的 main.tf 中,只单独保留 variables.tf 与 outputs.tf(符合要求)。 |
资源与后续步骤
- 完整代码仓库: KodeKloud Learning Labs
- 更多深度解析: Whispering Cloud Insights
- 讨论社区: DEV Community
致谢
- 实验内容最初来源于 KodeKloud。