用 gcloud storage 管理 Cloud Storage 桶与对象
破坏性操作:gcloud storage rm --recursive 和 rsync -d 会删除目标端对象;桶级生命周期规则到期也会自动删除。执行前确认桶已开启版本控制或软删除,删除的对象在保留期内可恢复;关闭保护后不可恢复。先用 ls --recursive 核对范围,或先复制到临时前缀。
Cloud Storage 桶名全局唯一,按位置和存储类计费。gcloud storage 是当前推荐工具,旧的 gsutil 仍可用但参数不同。统一桶级访问(UBLA)关闭 ACL,权限完全由 IAM 控制;公共访问保护可阻止误设 allUsers。
gcloud auth login
gcloud config set project example-project
gcloud storage buckets create gs://example-bucket-2026 \
--location=asia-east1 --uniform-bucket-level-access --public-access-prevention
gcloud storage ls gs://example-bucket-2026/
gcloud storage cp ./app.tar.gz gs://example-bucket-2026/app/
gcloud storage rsync -r ./dist gs://example-bucket-2026/dist
gcloud storage rsync -r -d ./dist gs://example-bucket-2026/dist
gcloud storage rm --recursive gs://example-bucket-2026/tmp
gcloud storage buckets update gs://example-bucket-2026 --versioning
gcloud storage buckets update gs://example-bucket-2026 \
--lifecycle-file=lifecycle.json
gcloud storage buckets add-iam-policy-binding gs://example-bucket-2026 \
--member=serviceAccount:deploy-sa@example-project.iam.gserviceaccount.com \
--role=roles/storage.objectViewer
gcloud storage objects update gs://example-bucket-2026/app/app.tar.gz \
--storage-class=NEARLINE
gcloud storage buckets describe gs://example-bucket-2026
生命周期 JSON 示例:
{
"rule": [{
"action": {"type": "Delete"},
"condition": {"age": 365, "matchesPrefix": ["tmp/"]}
}]
}
成本包括存储类、操作次数、提前删除罚金和出网流量;Nearline/Coldline/Archive 有 30/90/365 天最短存储期。本文基于当前 gcloud CLI,gsutil 与 gcloud storage 参数不同,以当前版本为准。
rm --recursive 会删除前缀下所有对象,且默认不进入回收站;先确认版本控制或软删除。rsync -d 会删除目标端多余对象;不加 -d 只见新增和更新。allUsers 绑定相互独立,先检查两者。gcloud storage rsync 加不加 -d 有什么区别?-d 只同步新增和更新;加 -d 会删除目标端源端不存在的对象。
小程序版
微信扫码,随时查命令