← All posts
2 min read
Restore an older S3 object version
#aws#cli#s3#storage#versioning
📑 On this page
Part 24 of AWS from Zero. Today we make an older value current again without destroying version history.
What we are learning
Copying a specific older version onto the same key creates a new current version containing the older data. The original versions remain available.
Before you run it
REGION="ap-south-1"
BUCKET="aws-zero-restore-version-12345"
KEY="settings.txt"
aws s3api create-bucket \
--bucket "$BUCKET" \
--region "$REGION" \
--create-bucket-configuration LocationConstraint="$REGION"
aws s3api put-bucket-versioning \
--bucket "$BUCKET" \
--versioning-configuration Status=Enabled
echo "stable settings" > settings.txt
STABLE_VERSION=$(aws s3api put-object \
--bucket "$BUCKET" \
--key "$KEY" \
--body settings.txt \
--query VersionId \
--output text)
echo "broken settings" > settings.txt
BROKEN_VERSION=$(aws s3api put-object \
--bucket "$BUCKET" \
--key "$KEY" \
--body settings.txt \
--query VersionId \
--output text)Inspect the history
aws s3api list-object-versions \
--bucket "$BUCKET" \
--prefix "$KEY" \
--query "Versions[].{Version:VersionId,Latest:IsLatest,Updated:LastModified}" \
--output tableRestore the stable version
RESTORED_VERSION=$(aws s3api copy-object \
--bucket "$BUCKET" \
--key "$KEY" \
--copy-source "$BUCKET/$KEY?versionId=$STABLE_VERSION" \
--query VersionId \
--output text)The copy receives a new version ID and becomes current.
Verify the content
aws s3 cp "s3://$BUCKET/$KEY" restored-settings.txt
cat restored-settings.txtYou should see stable settings.
One tiny variation
You can retrieve an old version without making it current:
aws s3api get-object \
--bucket "$BUCKET" \
--key "$KEY" \
--version-id "$BROKEN_VERSION" \
broken-settings.txtCommon mistake
The --copy-source value must be URL encoded when the key or version ID contains characters that are not safe in a URL. Always preserve the exact version ID returned by S3.
Restoring by copy creates another stored version, so it does not reduce storage usage.
Cleanup
aws s3api delete-object --bucket "$BUCKET" --key "$KEY" --version-id "$STABLE_VERSION"
aws s3api delete-object --bucket "$BUCKET" --key "$KEY" --version-id "$BROKEN_VERSION"
aws s3api delete-object --bucket "$BUCKET" --key "$KEY" --version-id "$RESTORED_VERSION"
aws s3api delete-bucket --bucket "$BUCKET" --region "$REGION"
rm settings.txt restored-settings.txt broken-settings.txtNext, we will configure and verify explicit SSE-S3 default encryption.