Skip to main content

Cloud and deployment · Intermediate · 20 min

Expire and archive old S3 objects automatically with lifecycle rules

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4

You will have a versioned S3 bucket whose lifecycle configuration archives and then deletes old logs, keeps three old versions of each backup, expires tagged exports after a week and cleans up abandoned multipart uploads, all from one JSON file you lint before applying.

On this page

A bucket that collects logs and backups only ever grows. Nobody deletes last March's access logs by hand, every nightly backup leaves another old version behind, and an upload that died halfway through can leave gigabytes of parts that no aws s3 ls will ever show you. S3 lifecycle rules fix this: you describe, once, what should happen to objects as they age, and S3 applies it every day without a script or a cron job.

In this tutorial you build a small bucket with the four kinds of clutter most teams have, then write one lifecycle configuration that deals with all of them:

  • objects under logs/ move to S3 Standard-IA after 30 days, to S3 Glacier Flexible Retrieval after 90, and are deleted after a year;
  • objects under backups/ keep their current version forever, plus the three most recent old versions;
  • objects under exports/ tagged retention=short are deleted after 7 days;
  • multipart uploads that were never finished are cleaned up after 7 days.

Along the way you lint the rules with a short jq script before AWS sees them, and you learn where lifecycle rules can cost more than they save. That happens with tiny files, and the cost comes from minimum storage durations and per-object fees.

Everything you create is named lifecycle-demo-... and your working files live in ~/lifecycle-demo. The bucket and its few small objects cost very little while they exist, and the last step deletes them.

Step 1 · Install the AWS CLI and confirm the account

Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version

If the AWS CLI is already installed, the installer stops and says so; run sudo ./aws/install --update instead. The CLI does not get updates from apt, so to upgrade later you run the same commands with a newer version number. The zip is a large download, so on a prepaid mobile bundle fetch it once over Wi-Fi and keep it.

Point the CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder); /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles shows how to set one up. Then check who you are:

Bash
aws sts get-caller-identity --query Account --output text

Check it worked

aws --version starts with aws-cli/2.42.4, and the second command prints the 12-digit ID of your sandbox account. If it prints a different account, stop and fix your profile before you create anything.

Step 2 · Make a bucket with logs, backups, exports and a stalled upload

Bucket names are shared by every AWS account in the world, so add a random suffix. Save the suffix and the Region in a small demo.env file, so a new terminal can pick them up with . ./demo.env:

Bash
mkdir -p ~/lifecycle-demo
cd ~/lifecycle-demo
SUFFIX=$(head -c 4 /dev/urandom | od -An -tx1 | tr -d ' \n')
cat > demo.env <<EOF
export AWS_REGION=eu-west-2
export BUCKET=lifecycle-demo-${SUFFIX}
EOF
. ./demo.env
echo "Your bucket will be ${BUCKET} in ${AWS_REGION}"

The examples use eu-west-2 (London). Any Region works if you use it everywhere, except that us-east-1 must be created without the --create-bucket-configuration line below. If you work from Africa and your account has the Cape Town Region (af-south-1) turned on, it is closer to you. It is an opt-in Region, and S3 prices differ from Region to Region.

Create the bucket and turn on versioning. Versioning keeps the old copy every time an object is overwritten or deleted, which is what you want for backups. It applies to the whole bucket, not one prefix, and that matters later:

Bash
aws s3api create-bucket --bucket "$BUCKET" --region "$AWS_REGION" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"
aws s3api put-bucket-versioning --bucket "$BUCKET" \
  --versioning-configuration Status=Enabled

Now add the clutter. Three small daily log files and one 300 KB monthly archive go under logs/:

Bash
mkdir -p logs
for d in 01 02 03; do
  seq 1 400 | sed "s|^|2026-11-$d GET /health 200 |" > "logs/app-2026-11-$d.log"
done
head -c 307200 /dev/urandom > logs/app-2026-10.tar.gz
aws s3 cp logs/ "s3://$BUCKET/logs/" --recursive

Upload the same nightly backup five times. Each upload replaces the current version and keeps the previous one as a noncurrent version:

Bash
for run in 1 2 3 4 5; do
  echo "backup run $run" | gzip > app-db.sql.gz
  aws s3api put-object --bucket "$BUCKET" --key backups/app-db.sql.gz \
    --body app-db.sql.gz --query VersionId --output text
done

Add a CSV export tagged for short retention:

Bash
printf 'order,total\n1001,12.50\n1002,8.00\n' > orders.csv
aws s3api put-object --bucket "$BUCKET" --key exports/orders-2026-11.csv \
  --body orders.csv --tagging 'retention=short'

Last, start a multipart upload, send one 1 MB part and walk away, as a backup job does when it crashes halfway:

Bash
UPLOAD_ID=$(aws s3api create-multipart-upload --bucket "$BUCKET" \
  --key backups/full-2026-11.tar --query UploadId --output text)
head -c 1048576 /dev/urandom > part1.bin
aws s3api upload-part --bucket "$BUCKET" --key backups/full-2026-11.tar \
  --part-number 1 --upload-id "$UPLOAD_ID" --body part1.bin
echo "export UPLOAD_ID=${UPLOAD_ID}" >> demo.env

Check it worked

aws s3 ls "s3://$BUCKET/" --recursive lists four log files, one backup and one export. The half-finished upload is not in that list, but aws s3api list-multipart-uploads --bucket "$BUCKET" --query 'Uploads[].Key' shows backups/full-2026-11.tar. Its part is stored and billed all the same. aws s3api list-object-versions --bucket "$BUCKET" --prefix backups/app-db.sql.gz --query 'Versions[].IsLatest' prints five values, one true and four false.

Step 3 · Write the lifecycle rules as one JSON file

A bucket has exactly one lifecycle configuration, holding up to 1,000 rules. Each rule has an ID, a Status (Enabled or Disabled), a Filter that picks objects, and one or more actions. Write all four rules into lifecycle.json:

Bash
cd ~/lifecycle-demo
cat > lifecycle.json <<'JSON'
{
  "Rules": [
    {
      "ID": "logs-tier-then-expire",
      "Status": "Enabled",
      "Filter": { "Prefix": "logs/" },
      "Transitions": [
        { "Days": 30, "StorageClass": "STANDARD_IA" },
        { "Days": 90, "StorageClass": "GLACIER" }
      ],
      "Expiration": { "Days": 365 },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 1 }
    },
    {
      "ID": "backups-keep-three-old-versions",
      "Status": "Enabled",
      "Filter": { "Prefix": "backups/" },
      "NoncurrentVersionExpiration": {
        "NoncurrentDays": 7,
        "NewerNoncurrentVersions": 3
      }
    },
    {
      "ID": "short-retention-exports",
      "Status": "Enabled",
      "Filter": {
        "And": {
          "Prefix": "exports/",
          "Tags": [{ "Key": "retention", "Value": "short" }]
        }
      },
      "Expiration": { "Days": 7 },
      "NoncurrentVersionExpiration": { "NoncurrentDays": 1 }
    },
    {
      "ID": "abort-stale-multipart-uploads",
      "Status": "Enabled",
      "Filter": { "Prefix": "" },
      "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
    }
  ]
}
JSON

Read it rule by rule:

  • logs-tier-then-expire counts days from when each object was written, rounded up to the next midnight UTC. STANDARD_IA is S3 Standard-Infrequent Access: same speed, cheaper storage, a fee per GB read. GLACIER is the API name for S3 Glacier Flexible Retrieval, which is cheaper again but cannot be read until you restore a copy, which takes minutes to hours. Expiration at 365 days deletes the object.
  • That NoncurrentVersionExpiration line in the logs rule is the one people forget. Because the bucket is versioned, "deleting" a log at day 365 only adds a delete marker and turns the log into a noncurrent version. Without this line, every expired log would sit there as an old version, still billed, forever. With it, the old version is removed a day later, and S3 also clears the leftover delete marker on its own, because the rule's Expiration uses Days.
  • backups-keep-three-old-versions never touches the current backup. An old version is deleted only when both conditions hold: it has been noncurrent for more than 7 days, and at least three newer old versions exist. So you always keep the live backup plus the last three, with a week to notice a bad overwrite. NewerNoncurrentVersions accepts 1 to 100.
  • short-retention-exports uses And, because it combines a prefix with a tag. An object must be under exports/ and carry retention=short; an untagged export is left alone. That lets the code that writes the file decide how long it lives.
  • abort-stale-multipart-uploads has an empty prefix, which matches every key in the bucket. It stops uploads that are still unfinished 7 days after they started, and deletes their parts. This action cannot go in a rule with a tag filter, which is why it has its own rule.

Rules may overlap, as the logs and multipart rules do here. When two actions fall on the same object on the same day, S3 prefers permanent deletion over a transition, and a transition over adding a delete marker.

Check it worked

jq -r '.Rules[].ID' lifecycle.json prints the four rule IDs in order, and jq '.Rules | length' lifecycle.json prints 4. If jq reports a parse error, compare the file with the one above: a missing comma is the usual cause.

Step 4 · Lint the rules before AWS sees them

AWS rejects some mistakes outright, and others it accepts and then bills you for. A short jq program catches the common ones on your machine, in milliseconds:

  • two rules with the same ID;
  • AbortIncompleteMultipartUpload in a rule with a tag filter (AWS rejects this);
  • a second transition that leaves a storage class before its minimum duration. Standard-IA has a 30-day minimum, Glacier Flexible Retrieval 90 days and Deep Archive 180, and one rule cannot move an object out of a class earlier than that;
  • an expiry that comes before the last class's minimum has passed. AWS accepts this, but it charges for the rest of the minimum anyway, so the lint reports it as a warning.

Save the program:

Bash
cat > lint.jq <<'JQ'
def minimum: {"STANDARD_IA": 30, "ONEZONE_IA": 30, "GLACIER_IR": 90,
              "GLACIER": 90, "DEEP_ARCHIVE": 180, "INTELLIGENT_TIERING": 0};
def has_tag_filter: [.Filter // {} | .. | objects | select(has("Tag") or has("Tags"))] | length > 0;

(.Rules | map(.ID) | group_by(.) | map(select(length > 1) | "error: duplicate rule ID \(.[0])") | .[]),
(.Rules[] | . as $r | (.Transitions // []) as $t |
  (if has_tag_filter and has("AbortIncompleteMultipartUpload")
   then "error: \($r.ID): AbortIncompleteMultipartUpload cannot use a tag filter" else empty end),
  (range(1; $t | length) as $i |
   if ($t[$i].Days - $t[$i-1].Days) < minimum[$t[$i-1].StorageClass]
   then "error: \($r.ID): \($t[$i].StorageClass) on day \($t[$i].Days) leaves \($t[$i-1].StorageClass) before its \(minimum[$t[$i-1].StorageClass])-day minimum"
   else empty end),
  (if ($r.Expiration.Days != null) and ($t | length) > 0
      and ($r.Expiration.Days - $t[-1].Days) < minimum[$t[-1].StorageClass]
   then "warn: \($r.ID): expires on day \($r.Expiration.Days), before the \(minimum[$t[-1].StorageClass])-day minimum in \($t[-1].StorageClass) is up"
   else empty end))
JQ

Run it on your file. The program prints one line per problem and nothing when the file is clean, so the wrapper turns silence into a clear message:

Bash
problems=$(jq -r -f lint.jq lifecycle.json)
if [ -z "$problems" ]; then echo "lint: no problems"; else echo "$problems"; fi

Fix every error line before you apply the file, and read every warn line before you decide to keep it.

Now prove it catches something. Make a broken copy that sends logs to Glacier on day 45, only 15 days after they reached Standard-IA:

Bash
jq '(.Rules[0].Transitions[1].Days) = 45' lifecycle.json > broken.json
jq -r -f lint.jq broken.json

Check it worked

The first run prints lint: no problems. The broken copy prints one line starting error: logs-tier-then-expire: GLACIER on day 45 leaves STANDARD_IA before its 30-day minimum. Delete it with rm broken.json once you have seen the message.

Step 5 · Apply the configuration and read it back

Applying a configuration replaces whatever lifecycle rules the bucket already has. On a new bucket that is nothing, but on a bucket you did not create, someone may have added rules in the console. Save the live rules first. The --query keeps only Rules, because the full answer also holds a TransitionDefaultMinimumObjectSize field that the put command will not accept back. On a bucket with no rules the command fails with NoSuchLifecycleConfiguration, which is fine:

Bash
cd ~/lifecycle-demo
. ./demo.env
aws s3api get-bucket-lifecycle-configuration --bucket "$BUCKET" \
  --query '{Rules: Rules}' > lifecycle-before.json \
  || echo "No existing lifecycle rules on $BUCKET"

Apply your file:

Bash
aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" \
  --lifecycle-configuration file://lifecycle.json

AWS answers with one field, "TransitionDefaultMinimumObjectSize": "all_storage_classes_128K". That is the default since September 2024: objects smaller than 128 KB are never transitioned to another storage class, though they still expire. The next step explains why that default protects you.

Read the rules back, one line per rule:

Bash
aws s3api get-bucket-lifecycle-configuration --bucket "$BUCKET" \
  --query 'Rules[].[ID, Status]' --output text

The new configuration takes a few minutes to reach all of S3. It then applies to objects already in the bucket as well as new ones: a log that was already 400 days old would be queued for deletion at once. S3 runs the actions in the background with no promised completion time. Your bill changes on the day a rule is satisfied, even if the object moves or disappears days later. For deletions that must happen by a legal or contractual deadline, do not rely on lifecycle alone: check with an S3 Inventory report or a listing, and delete what is overdue yourself.

On AWS, once the rules have spread, S3 also tells you which rule will delete an object and when:

Bash
aws s3api head-object --bucket "$BUCKET" --key logs/app-2026-11-01.log \
  --query Expiration --output text

Expect something like expiry-date="Wed, 18 Nov 2027 00:00:00 GMT", rule-id="logs-tier-then-expire".

Check it worked

The read-back prints four lines, each a rule ID followed by Enabled. aws s3api get-bucket-lifecycle-configuration --bucket "$BUCKET" --query "Rules[?ID=='logs-tier-then-expire'].Transitions[].StorageClass" --output text prints STANDARD_IA and GLACIER.

Step 6 · Check whether moving small files saves money

Moving objects to colder classes is not free, and on small files it can cost more than it saves. Three facts decide it:

  • Every transition is a request, and requests are billed. One object moved is one transition request, charged per 1,000 at a rate set for each Region on the S3 pricing page. A million small log files means a million requests, however little data they hold.
  • Minimum durations and sizes. Standard-IA bills at least 30 days and at least 128 KB per object. Glacier Flexible Retrieval bills at least 90 days, and Deep Archive 180. Delete earlier and you pay for the rest of the minimum.
  • Archive overhead. Every object in Glacier Flexible Retrieval or Deep Archive carries 40 KB of extra billed storage: 8 KB at S3 Standard rates and 32 KB at the archive rate.

Work it through for 100,000 log files of 20 KB each, about 2 GB of data. Archived one by one, they would add about 4 GB of overhead, twice the data itself, plus 100,000 transition requests. That is why S3 now skips objects under 128 KB by default. It is also why the better fix for small logs is to bundle them, for example one compressed tar per day, before you upload.

See how many of your own log objects are under the 128 KB line:

Bash
cd ~/lifecycle-demo
. ./demo.env
aws s3api list-objects-v2 --bucket "$BUCKET" --prefix logs/ \
  --query 'Contents[?Size < `131072`].Key' --output text
aws s3api list-objects-v2 --bucket "$BUCKET" --prefix logs/ \
  --query 'Contents[?Size >= `131072`].[Key, Size]' --output text

With the default in place, only the 300 KB archive will ever move to Standard-IA and Glacier. The three daily files stay in S3 Standard until they expire on day 365, which is what you want. To move smaller objects anyway, add ObjectSizeGreaterThan (in bytes) to the rule's filter, inside an And with the prefix. Do the sum above first.

Lifecycle transitions suit data whose access pattern you know, like logs that nobody reads after a month. When you do not know the pattern, for example files your users upload, S3 Intelligent-Tiering is usually the simpler answer. It moves each object between access tiers based on real reads, with no retrieval fees and no minimum duration, for a small monthly monitoring fee per object. Objects under 128 KB are not monitored and stay in its Frequent Access tier. A rule that puts a prefix into Intelligent-Tiering on day 0 looks like this:

JSON
{
  "ID": "uploads-to-intelligent-tiering",
  "Status": "Enabled",
  "Filter": { "Prefix": "uploads/" },
  "Transitions": [{ "Days": 0, "StorageClass": "INTELLIGENT_TIERING" }]
}

Check it worked

The first query prints the three app-2026-11-*.log keys, and the second prints logs/app-2026-10.tar.gz with a size of 307200. You can now explain, for any prefix in your own buckets, whether a transition rule would pay for itself.

Step 7 · Change one rule without losing the others

Because a put replaces everything, you change a rule by editing the whole file and putting it again. Never write a one-rule file "to fix only that rule": it would delete the other three. Keep lifecycle.json in Git next to your infrastructure code, so the file is the record of what the bucket should do.

Suppose the team wants to keep exports for now. Turn that rule off rather than deleting it, so it can come back later. Writing to a new file and then renaming it keeps the original intact if jq fails:

Bash
cd ~/lifecycle-demo
. ./demo.env
jq '(.Rules[] | select(.ID == "short-retention-exports") | .Status) = "Disabled"' \
  lifecycle.json > lifecycle.next.json
mv lifecycle.next.json lifecycle.json
jq -r -f lint.jq lifecycle.json
aws s3api put-bucket-lifecycle-configuration --bucket "$BUCKET" \
  --lifecycle-configuration file://lifecycle.json
aws s3api get-bucket-lifecycle-configuration --bucket "$BUCKET" \
  --query 'Rules[].[ID, Status]' --output text

Disabling a rule stops S3 scheduling new work for it after a short delay, and objects it had already scheduled are unscheduled.

Check it worked

The lint prints nothing. The read-back still lists four rules: short-retention-exports now shows Disabled and the other three show Enabled.

Step 8 · Clean up

A versioned bucket can only be deleted once every version and delete marker is gone, and the stalled upload must be stopped too. The commands below permanently delete everything in the bucket named in $BUCKET. The first line refuses to go on unless that name starts with lifecycle-demo-:

Bash
cd ~/lifecycle-demo
. ./demo.env
case "$BUCKET" in lifecycle-demo-*) echo "Deleting $BUCKET" ;; *) echo "BUCKET is not the demo bucket"; false ;; esac
aws s3api abort-multipart-upload --bucket "$BUCKET" \
  --key backups/full-2026-11.tar --upload-id "$UPLOAD_ID"
aws s3api delete-bucket-lifecycle --bucket "$BUCKET"
aws s3api list-object-versions --bucket "$BUCKET" --output json \
  | jq '{Objects: [(.Versions // [])[], (.DeleteMarkers // [])[] | {Key, VersionId}], Quiet: true}' \
  > delete.json
aws s3api delete-objects --bucket "$BUCKET" --delete file://delete.json
aws s3api delete-bucket --bucket "$BUCKET"
cd ~
rm -rf ~/lifecycle-demo

delete-objects takes up to 1,000 keys per call, which is plenty here. For a large bucket, emptying it with a lifecycle rule (expire current versions after 1 day, noncurrent after 1 day, abort uploads after 1 day) and deleting it once it is empty avoids thousands of API calls.

Check it worked

aws s3api head-bucket --bucket "$BUCKET" now fails with a 404 (Not Found) error, and ls ~/lifecycle-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.