Expire old S3 objects with a lifecycle rule
📑 On this page
Part 48 of AWS from Zero. This lesson keeps the scope to one S3 behavior you can verify from the terminal.
What we are learning
Lifecycle expiration lets S3 remove matching objects after a defined age. The rule should use a narrow filter and a descriptive ID.
Before you run it
aws sts get-caller-identity
REGION="ap-south-1"
BUCKET="replace-with-your-private-demo-bucket"Use a private general purpose bucket that you own. Replace every placeholder before running a write or delete command.
The command
cat > lifecycle-expire.json <<'EOF'
{
"Rules": [{
"ID": "ExpireTemporaryFiles",
"Status": "Enabled",
"Filter": {"Prefix": "temporary/"},
"Expiration": {"Days": 30}
}]
}
EOF
aws s3api put-bucket-lifecycle-configuration \
--bucket "$BUCKET" \
--lifecycle-configuration file://lifecycle-expire.jsonA successful configuration command may return no output. Treat inspection as a separate required step.
Inspect the result
aws s3api get-bucket-lifecycle-configuration \
--bucket "$BUCKET" \
--query "Rules[].{ID:ID,Status:Status,Prefix:Filter.Prefix,ExpireDays:Expiration.Days}" \
--output tableRead the returned fields rather than assuming the write succeeded exactly as intended.
One tiny variation
sed 's/"Status": "Enabled"/"Status": "Disabled"/' lifecycle-expire.json > lifecycle-disabled.jsonA disabled rule remains documented but performs no lifecycle actions.
Common mistake
put-bucket-lifecycle-configuration replaces the bucket's entire lifecycle configuration. Include existing rules you intend to keep.
Cleanup
aws s3api delete-bucket-lifecycle --bucket "$BUCKET"
rm lifecycle-expire.json lifecycle-disabled.jsonDeleting the configuration stops future lifecycle actions but does not restore objects already expired.
Next, we will learn Transition S3 objects to Standard-IA with lifecycle.