Enable S3 Versioning from zero
📑 On this page
Part 22 of AWS from Zero. Today one object key starts keeping history.
What we are learning
When S3 Versioning is enabled, each new upload to the same key receives a unique version ID. Older versions remain stored and continue to incur normal storage charges.
Before you run it
REGION="ap-south-1"
BUCKET="aws-zero-versioning-12345"
KEY="config.txt"
aws s3api create-bucket \
--bucket "$BUCKET" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION"Enable versioning
aws s3api put-bucket-versioning \
--bucket "$BUCKET" \
--versioning-configuration Status=EnabledVerify the state:
aws s3api get-bucket-versioning --bucket "$BUCKET"AWS recommends waiting 15 minutes after enabling versioning for the first time before depending on new object writes in a production workflow.
Create two versions
echo "version one" > config.txt
VERSION_ONE=$(aws s3api put-object \
--bucket "$BUCKET" \
--key "$KEY" \
--body config.txt \
--query VersionId \
--output text)
echo "version two" > config.txt
VERSION_TWO=$(aws s3api put-object \
--bucket "$BUCKET" \
--key "$KEY" \
--body config.txt \
--query VersionId \
--output text)Inspect the versions
aws s3api list-object-versions \
--bucket "$BUCKET" \
--prefix "$KEY" \
--query "Versions[].{Key:Key,Version:VersionId,Latest:IsLatest,Updated:LastModified}" \
--output tableThe second upload is current, but the first version still exists.
One tiny variation
Download the first version:
aws s3api get-object \
--bucket "$BUCKET" \
--key "$KEY" \
--version-id "$VERSION_ONE" \
old-config.txtCommon mistake
Suspending versioning does not delete existing versions. It changes how future writes are versioned. Version history and its storage cost must still be managed.
Cleanup
Delete both versions explicitly:
aws s3api delete-object --bucket "$BUCKET" --key "$KEY" --version-id "$VERSION_ONE"
aws s3api delete-object --bucket "$BUCKET" --key "$KEY" --version-id "$VERSION_TWO"
aws s3api delete-bucket --bucket "$BUCKET" --region "$REGION"
rm config.txt old-config.txtNext, we will see what a normal delete does inside a versioned bucket.