前提条件
安装 Terraform 从 Terraform 官网 下载并安装对应操作系统的版本。
配置 AWS 凭证 确保已安装 AWS CLI 并配置了凭证(
aws configure
),或直接在 Terraform 中通过provider
配置凭证。IAM 权限 确保 AWS 用户具有
AmazonS3FullAccess
权限。
步骤 1:创建 Terraform 配置文件
1.1 创建项目目录
mkdir terraform-s3 && cd terraform-s3
1.2 创建 provider.tf
定义 AWS Provider 配置:
# provider.tf
provider "aws" {
region = "us-east-1" # 按需修改区域
}
1.3 创建 s3_bucket.tf
定义 S3 存储桶资源:
# s3_bucket.tf
resource "aws_s3_bucket" "example_bucket" {
bucket = "my-unique-bucket-name-12345" # 存储桶名称需全局唯一
tags = {
Name = "ExampleBucket"
Environment = "Dev"
}
}
# 可选:启用版本控制
resource "aws_s3_bucket_versioning" "example_versioning" {
bucket = aws_s3_bucket.example_bucket.id
versioning_configuration {
status = "Enabled"
}
}
# 可选:阻止意外删除
resource "aws_s3_bucket_acl" "example_acl" {
bucket = aws_s3_bucket.example_bucket.id
acl = "private"
}
# 可选:强制销毁保护(默认false)
resource "aws_s3_bucket" "example_bucket" {
# ... 其他参数 ...
force_destroy = false # 设置为 true 允许非空存储桶被删除
}
1.4 创建 variables.tf
(可选)
定义变量以便复用:
# variables.tf
variable "bucket_name" {
description = "S3 存储桶名称"
type = string
default = "my-unique-bucket-name-12345"
}
1.5 创建 outputs.tf
(可选)
输出存储桶信息:
# outputs.tf
output "bucket_arn" {
value = aws_s3_bucket.example_bucket.arn
}
步骤 2:初始化并应用配置
2.1 初始化 Terraform
terraform init
这会下载 AWS Provider 插件。
2.2 生成执行计划
terraform plan
检查计划是否符合预期(如资源名称、区域等)。
2.3 创建存储桶
terraform apply
输入 yes
确认执行。
步骤 3:验证结果
AWS 控制台验证 登录 AWS 控制台,进入 S3 服务,查看是否创建成功。
AWS CLI 验证
aws s3 ls | grep "my-unique-bucket-name-12345"
步骤 4:销毁资源(可选)
terraform destroy
输入 yes
确认删除存储桶(确保存储桶为空)。
扩展配置示例
启用加密
resource "aws_s3_bucket_server_side_encryption_configuration" "example_encryption" {
bucket = aws_s3_bucket.example_bucket.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256" # 或使用 "aws:kms"
}
}
}
静态网站托管
resource "aws_s3_bucket_website_configuration" "example_website" {
bucket = aws_s3_bucket.example_bucket.id
index_document { suffix = "index.html" }
error_document { key = "error.html" }
}
设置访问权限
resource "aws_s3_bucket_policy" "example_policy" {
bucket = aws_s3_bucket.example_bucket.id
policy = data.aws_iam_policy_document.example_policy.json
}
data "aws_iam_policy_document" "example_policy" {
statement {
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.example_bucket.arn}/*"]
principals {
type = "AWS"
identifiers = ["*"]
}
}
}
常见问题
权限错误 确保 AWS 凭证正确,IAM 用户有足够权限。
存储桶名称冲突 S3 存储桶名称必须全局唯一,尝试添加随机后缀。
删除非空存储桶 设置
force_destroy = true
或在销毁前手动清空存储桶。