在打印窗口把「目标」选为「另存为 PDF」即可保存,页面已带 awsgood.com 版权水印。 返回原文

www.awsgood.com

How to Enable Versioning on S3 Bucket: Dev, Staging, Prod

2026-11-21 AWS Configuration 约 5 分钟

TL;DR

Versioning has three states, and two of them cost money

A bucket is either unversioned (never enabled), enabled, or suspended. get-bucket-versioning returns {} for the first case, which trips people up — an empty result is not an error, it means "off since birth."

aws s3api get-bucket-versioning --bucket acme-dev-assets --region us-east-1


```json
{}


Once you enable versioning, every `PutObject` gets a version ID and you are billed for each copy in full. S3 does not store deltas. Overwrite a 500 MB nightly export 20 times and you're storing 10 GB, not 500 MB. I've watched a bucket go from 12 GB to 310 GB in seven weeks because a sync job rewrote the same 40 objects every night and nobody had written a `NoncurrentVersionExpiration` rule. That's roughly $0.023/GB-month in us-east-1 for Standard — check your own region — times 300 GB of junk you'll never read.

Suspending versioning is the "off switch" people think they want. It stops new versions from being created, but every existing version stays and keeps billing. New writes land under version ID `null`, and if a `null` version already exists from before, the write overwrites it. You cannot get back to a truly unversioned bucket without deleting every version and the bucket itself.

## The per-environment settings that actually differ

Here's the diff I use for three-account setups. The versioning *status* is identical everywhere; the retention policy is what diverges.

| Setting | dev | staging | prod |
|---|---|---|---|
| Versioning status | Enabled | Enabled | Enabled |
| `NoncurrentVersionExpiration` | 7 days | 30 days | 90 days |
| `NewerNoncurrentVersions` kept | 3 | 10 | 30 |
| Noncurrent transition to Glacier Instant Retrieval | none | after 14 days | after 30 days |
| `AbortIncompleteMultipartUpload` | 1 day | 3 days | 7 days |
| `ExpiredObjectDeleteMarker` cleanup | on | off | off |
| MFA Delete | off | off | on for regulated buckets |
| Replication | none | none | CRR to us-west-2 |
| Who can call `PutBucketVersioning` | any engineer | team lead | break-glass role only |

The combination of `NewerNoncurrentVersions` and `NoncurrentDays` is the one most people get wrong. A version only becomes eligible for expiration when it is older than `NoncurrentDays` *and* ranks below the newest `NewerNoncurrentVersions`. That's exactly the behavior you want on prod: a bad Friday deploy shouldn't push your last good build out of the retention window because it happened to be 91 days old.

Here's the lifecycle rule for dev — note the aggressive delete-marker cleanup, which prod does not get:

```bash
cat > lifecycle-dev.json <<'EOF'
{
  "Rules": [
    {
      "ID": "trim-noncurrent",
      "Status": "Enabled",
      "Filter": { "Prefix": "" },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 7, "NewerNoncurrentVersions": 3 },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 1 },
      "Expiration": { "ExpiredObjectDeleteMarker": true }
    }
  ]
}
EOF

aws s3api put-bucket-lifecycle-configuration 
  --bucket acme-dev-assets 
  --lifecycle-configuration file://lifecycle-dev.json


`ExpiredObjectDeleteMarker: true` removes delete markers that have nothing beneath them. On dev that keeps `list-object-versions` readable. On prod I leave it off because a marker is sometimes the only breadcrumb showing someone deleted the wrong prefix.

## Copy-paste: enable, verify, suspend

The CLI has no `--versioning` flag on `create-bucket`; it's always a second call. Order matters if you're scripting bucket creation — versioning must be on before you attach certain policies or try to enable Object Lock.

```bash
# 1. Enable per environment
for b in acme-dev-assets acme-staging-assets acme-prod-assets; do
  aws s3api put-bucket-versioning 
    --bucket "$b" 
    --versioning-configuration Status=Enabled 
    --region us-east-1
done

# 2. Confirm (expect {"Status": "Enabled"})
aws s3api get-bucket-versioning --bucket acme-prod-assets --region us-east-1

# 3. Confirm writes really carry a version ID
aws s3api put-object --bucket acme-prod-assets --key probe.txt --body probe.txt
# {"ETag": ""d41d8cd98f00b204e9800998ecf8427e"", "VersionId": "9gGJ8YvX3Kq..._Z"}

# 4. Suspend (staging only, during a migration window)
aws s3api put-bucket-versioning 
  --bucket acme-staging-assets 
  --versioning-configuration Status=Suspended


Verification checklist per environment, in the order I run it:

1. `get-bucket-versioning` returns `{"Status": "Enabled"}` — not empty, not `Suspended`.
2. A test `put-object` returns a real `VersionId`, not `null`.
3. `get-bucket-lifecycle-configuration` shows the `NoncurrentVersionExpiration` block you expect for that env.
4. `list-object-versions --prefix <hot prefix>` shows noncurrent entries with `IsLatest: false`.
5. In CloudTrail, the `PutBucketVersioning` event from your change is visible with the right principal — that's your audit trail if a lifecycle rule later goes sideways.

One gotcha worth internalizing: `aws s3 ls` and `aws s3 cp` do not surface version IDs. If a script needs the ID, use `s3api put-object`, not `s3 cp`, or you'll be parsing the wrong tool's output.

## Keeping three accounts honest: Terraform variables and a CloudTrail tripwire

`aws_s3_bucket_versioning` is a separate resource from the bucket for a reason — AWS split it out in provider v4 precisely so a config change to versioning shows up as its own diff instead of hiding inside a bucket resource rewrite.

```hcl
locals {
  env_versioning = {
    dev     = { noncurrent_days = 7,  keep_newer = 3 }
    staging = { noncurrent_days = 30, keep_newer = 10 }
    prod    = { noncurrent_days = 90, keep_newer = 30 }
  }
}

resource "aws_s3_bucket_versioning" "assets" {
  bucket = aws_s3_bucket.assets.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_lifecycle_configuration" "assets" {
  bucket = aws_s3_bucket.assets.id

  rule {
    id     = "trim-noncurrent"