S3 操作速查
核心 S3 命令
# 列出桶
aws s3 ls
# 列出对象(含大小和日期)
aws s3 ls s3://my-bucket/ --human-readable --summarize
# 本地复制到 S3
aws s3 cp ./report.pdf s3://my-bucket/reports/report.pdf
# 同步目录(仅同步变更文件)
aws s3 sync ./dist s3://my-bucket/web --delete
# 创建 / 删除桶
aws s3 mb s3://my-new-bucket --region ap-southeast-1
aws s3 rb s3://my-empty-bucket
# 移动
aws s3 mv s3://my-bucket/old.txt s3://my-bucket/new.txt
生命周期规则
{
"Rules": [
{
"ID": "MoveToIA",
"Status": "Enabled",
"Filter": {"Prefix": "logs/"},
"Transitions": [
{"Days": 30, "StorageClass": "STANDARD_IA"},
{"Days": 90, "StorageClass": "GLACIER"}
],
"Expiration": {"Days": 365}
}
]
}
# 应用生命周期配置
aws s3api put-bucket-lifecycle-configuration \
--bucket my-bucket \
--lifecycle-configuration file://lifecycle.json
预签名 URL
# 生成预签名 GET URL(1 小时有效)
aws s3 presign s3://my-bucket/private/doc.pdf --expires-in 3600
# 使用 curl 访问预签名 URL
curl -o downloaded.pdf "https://my-bucket.s3.amazonaws.com/..."
桶策略
# 公开读取策略(静态网站托管)
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-website-bucket/*"
}]
}
# 应用桶策略
aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json
CORS 配置
{
"CORSRules": [{
"AllowedHeaders": ["Authorization", "Content-Type"],
"AllowedMethods": ["GET", "PUT", "POST"],
"AllowedOrigins": ["https://example.com"],
"ExposeHeaders": ["ETag"],
"MaxAgeSeconds": 3600
}]
}
aws s3api put-bucket-cors \
--bucket my-bucket \
--cors-configuration file://cors.json
存储类型
| 类型 | 使用场景 | 检索时间 |
|---|---|---|
| STANDARD | 频繁访问数据 | 即时 |
| STANDARD_IA | 低频访问、需快速检索 | 即时 |
| INTELLIGENT_TIERING | 访问模式不确定 | 即时 |
| GLACIER | 长期归档 | 数分钟至数小时 |
| DEEP_ARCHIVE | 合规归档 | 最长 12 小时 |