Homeβ€Ί Blogβ€Ί Week 8 - S3 Intelligent Storage Platform: Tiering,…
AWS Weekly Lab AWS Terraform

S3 Intelligent Storage Platform: Tiering, Lifecycle, and Cost Automation

S3 costs grow invisibly β€” objects uploaded once, never moved, billed at Standard rates for years. This platform automates tiering, enforces lifecycle rules, and emails you a daily savings report showing exactly what the automation earned.

AWS Platform Engineering Lab Β· Week 08

Lab Overview

An S3 bucket fills up. Which of those objects is anyone still reading?

The problem. Logs, exports, backups and media all land in Standard and stay there, because nobody goes back to reclassify them. Cost reviews at scale routinely find 60–80% of a bucket cold for months while still billed at the hot rate.

The objective. Let AWS decide where the access pattern is unknown, write deterministic rules where it is known, and mail the bill daily so the result is visible rather than assumed.

The outcome. It deploys and runs. The first daily report comes back empty, for a reason worth knowing before you call it broken.

Cloud Services and Concepts

ServicePurpose hereWhat it is
Amazon S3The bucket everything in this lab is aboutObject storage: you put files (objects) into buckets and pay for what you store and for each request, with no disk to size in advance.
S3 Intelligent-TieringMoves objects between tiers without anyone decidingA storage class that watches how often an object is read and moves it to a cheaper tier when it goes cold, for a small per-object monitoring charge.
S3 Lifecycle rulesTransitions by age, and the housekeepingRules on a bucket that act on an object's age: change its storage class, expire it, or clean up noncurrent versions and abandoned multipart uploads.
AWS LambdaTags objects on upload, and reports the billRuns a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs.
Amazon EventBridgeRuns the cost report once a dayAn event bus. Services and your own code publish events to it, and rules decide which events reach which targets β€” including on a schedule.
Amazon SNSDelivers the daily report by emailA publish-and-subscribe topic. One message is fanned out to every subscriber β€” email, a queue, or a function.
Amazon SQSThe dead-letter queue behind the taggerA queue that holds messages until something collects them, including the ones a function failed to process.
Amazon CloudWatchWhere the storage metrics come fromAWS's metrics and logs service. Most services publish into it automatically β€” S3 storage metrics once a day, not continuously.

S3 Storage Classes

S3 has seven storage classes. The ones that matter here:

ClassUse WhenPrice (us-east-1, July 2026)
StandardFrequent access, unknown access pattern$0.023/GB/month
Standard-IAInfrequent access, retrieval in milliseconds$0.0125/GB/month
Glacier Instant RetrievalArchive, retrieval in milliseconds$0.004/GB/month
Glacier Deep ArchiveLong-term archive, 12h retrieval$0.00099/GB/month

Prices verified 2026-06-30. Always check aws.amazon.com/s3/pricing/ for current rates.

Architecture and Workflow

Two independent automation paths run on the same bucket. The event-driven path (S3 β†’ SQS β†’ Lambda) tags every new object. The scheduled path (EventBridge β†’ Lambda β†’ SNS) delivers the daily savings report.

aws AWS Cloud Storage Amazon S3 versioned, encrypted, private Intelligent-Tiering: Frequent to IA at 30d, Archive IR at 90d, Deep at 180d Lifecycle: abort incomplete uploads at 7d, expire noncurrent versions at 30d The tiering is automatic. The lifecycle rules are the part that actually deletes anything. SQS queue buffers the events 1 object tagger content-type, upload-date 2 dead-letter queue after 3 failures alarm DLQ depth above 0 3 EventBridge rate(1 day) cost reporter reads the cost delta 4 SNS daily email

Why SQS Between S3 and Lambda?

S3 supports direct Lambda triggers. The production reason to use SQS instead: at high object creation rates, direct S3 β†’ Lambda triggers can throttle or drop events. SQS provides buffering β€” events queue up and Lambda processes them at its own pace. The DLQ gives you visibility when the tagger fails; without it, a tagging failure would silently disappear.

Why Lambda for Both Functions?

Both workloads fit Lambda’s constraints cleanly. The object tagger: event-triggered, stateless, completes in under a second, essentially zero base concurrency. The cost reporter: runs once per day, needs about 5 seconds to call CloudWatch and SNS, produces no output beyond the email. Neither workload has duration (ECS), parallelism (Batch), or orchestration (Step Functions) characteristics. Lambda is the right tool here β€” not because it was used in prior weeks, but because the workload shape matches.

Prerequisites

RequirementWhyHow to check
An HCP Terraform workspace with OIDC into an AWS roleKeeps credentials out of the repo and out of CIThe workspace assumes the role on each run; no static keys exist anywhere
An email address you can read during the applyAn SNS subscription is pending until the confirmation link is clicked, and an unconfirmed topic delivers nothing while reporting successaws sns list-subscriptions-by-topic shows an ARN rather than PendingConfirmation
A day of patience before judging the reportS3 storage metrics in CloudWatch are published roughly daily, so the first report is legitimately empty β€” this is not a bug in the reporterThe first report says so; the second has numbers
Terraform with the AWS providerEverything here is declared; nothing is clickedterraform version

Implementation

Step 1 β€” Terraform Structure

Two Terraform modules under week-08-s3-intelligent-storage/terraform/modules/:

  • s3-storage β€” the bucket, IT config, lifecycle rules, and bucket notification
  • cost-automation β€” SQS, DLQ, both Lambdas, EventBridge rule, SNS topic, IAM roles, CloudWatch alarm

The two modules began with a circular dependency. Both now take the bucket name as a variable and build the ARNs themselves.

HCL
locals {
  account_id     = data.aws_caller_identity.current.account_id
  name_prefix    = "${var.project}-${var.environment}"
  bucket_name    = "${local.name_prefix}-${local.account_id}"
  bucket_arn     = "arn:aws:s3:::${local.bucket_name}"
  sqs_queue_name = "${local.name_prefix}-object-events"
  sqs_queue_arn  = "arn:aws:sqs:${var.aws_region}:${local.account_id}:${local.sqs_queue_name}"
}

Neither module output feeds the other β€” Terraform can plan and apply both in parallel with no dependency graph cycle.

Step 2 β€” S3 Intelligent-Tiering Configuration

Intelligent-Tiering is a bucket-level rule with no prefix filter, so it covers every object. Archive Instant activates at 90 days without access, Deep Archive at 180.

HCL
resource "aws_s3_bucket_intelligent_tiering_configuration" "main" {
  bucket = aws_s3_bucket.main.id
  name   = "EntireBucket"

  tiering {
    access_tier = "ARCHIVE_ACCESS"
    days        = var.intelligent_tiering_archive_days  # 90
  }
  tiering {
    access_tier = "DEEP_ARCHIVE_ACCESS"
    days        = var.intelligent_tiering_deep_archive_days  # 180
  }
}

Step 3 β€” Lifecycle Policies

Three lifecycle rules on the same bucket:

  • logs/ prefix rule β€” Standard-IA at 30d, Glacier Instant Retrieval at 90d, delete at 365d
  • AbortIncompleteMultipartUpload β€” kills orphaned upload parts after 7 days (silent cost if skipped)
  • NoncurrentVersionExpiration β€” expires old versions after 30 days (versioning is on; without this, every overwrite retains prior versions forever)

Step 4 β€” SQS + DLQ + Lambda: object_tagger

The queue policy allows SendMessage only from this bucket. The Lambda reads the queue, classifies each object by prefix and tags it; what it cannot process lands in the dead-letter queue.

Python
def classify_object(key: str) -> str:
    key_lower = key.lower()
    if key_lower.startswith("logs/"):
        return "logs"
    if key_lower.startswith("data/"):
        return "data"
    if key_lower.startswith("media/"):
        return "media"
    if key_lower.startswith("archive/"):
        return "archive"
    if any(key_lower.endswith(ext) for ext in [".log", ".txt", ".csv"]):
        return "logs"
    return "data"

Step 5 β€” EventBridge + Lambda: storage_cost_reporter

A daily EventBridge rule invokes the reporter, which reads BucketSizeBytes per storage tier from CloudWatch and publishes the total to SNS.

Step 6 β€” Deploy via HCP Terraform

Backend is HCP Terraform Cloud (same pattern as weeks 5, 6, 7):

HCL
cloud {
  organization = "Katta"
  workspaces {
    name = "week-08-dev"
  }
}

A VCS-connected HCP workspace runs the apply.

The plan showed 25 resources across both modules.

After adding depends_on = [module.cost_automation] to the s3_storage module, re-applying created the remaining resource cleanly:

HCP apply finished successfully with 25 resources created and outputs shown
Second apply: 1 resource added β€” all 25 created, bucket name and reporter function name in outputs

Step 7 β€” Verify S3 Configuration in the Console

After the apply, the bucket, its tiering configuration and its lifecycle rules:

S3 bucket in the AWS console
S3 bucket created with versioning enabled, SSE-S3 encryption, and public access fully blocked
S3 Intelligent-Tiering configuration in the AWS console
Intelligent-Tiering config: Archive Instant at 90 days, Deep Archive at 180 days, applied bucket-wide
S3 lifecycle rules showing logs prefix transitions and cleanup rules
Three lifecycle rules: logs/ prefix transitions, AbortIncompleteMultipartUpload (7d), NoncurrentVersionExpiration (30d)

Step 9 β€” Test Object Tagging

A test object in the logs/ prefix, tagged by the pipeline:

bash
echo "test log entry" | aws s3 cp - s3://$BUCKET/logs/app/2026-07-02.log --profile personal
S3 object showing content-type: logs and upload-date tags applied by the object_tagger Lambda
Object tags applied by object_tagger Lambda: content-type: logs, upload-date: 2026-07-03

Step 10 β€” Invoke the Cost Reporter Manually

Invoking the reporter by hand returned StatusCode 200 with total_bytes 0: CloudWatch S3 metrics lag about 24 hours, so on day one there was genuinely nothing to report.

bash
aws lambda invoke \
  --function-name week-08-s3-storage-dev-storage-reporter \
  --invocation-type RequestResponse \
  out.json --profile personal && cat out.json
Lambda storage_cost_reporter invocation returning StatusCode 200 with zero total bytes
storage_cost_reporter invoked: StatusCode 200, total_bytes 0 (CloudWatch S3 metrics have 24h delay β€” expected on first run)

The next morning the schedule fired on its own and delivered the first real report:

SNS email report in Gmail: S3 Storage Cost Report showing no data yet, CloudWatch metrics take 24 hours
Daily SNS email report delivered to inbox: EventBridge fired, Lambda ran, SNS published β€” message correctly notes CloudWatch S3 metrics take 24h to appear after bucket creation

Validation and Evidence

Each row traces to a figure in this post. The lab was destroyed in July 2026, so these are the results recorded then, not a fresh run.

TestExpectedActualStatus
The platform deploys25 resources24 on the first apply β€” the bucket notification failed on SQS queue-policy propagation β€” then all 25 on a re-run with no change to the codePass on retry
The bucket is hardenedVersioning on, SSE-S3 encryption, public access fully blockedAll three confirmed in the consolePass
Intelligent-Tiering is configuredArchive Instant at 90 days, Deep Archive at 180, bucket-wideApplied bucket-wide as declaredPass
Lifecycle rules existThree: logs/ to Standard-IA at 30 days, Glacier Instant Retrieval at 90 and deletion at 365; abort incomplete multipart uploads at 7 days; expire noncurrent versions at 30All three presentPass
Objects are tagged on uploadcontent-type and upload-date applied by the taggercontent-type: logs, upload-date: 2026-07-03Pass
The tagger has no failuresAn empty dead-letter queueDLQ message count zeroPass
The daily report is deliveredAn email, on a schedule, with the bucket's sizeDelivered. StatusCode 200, total_bytes 0 β€” the report correctly said there was no data yet, because S3 storage metrics lag about 24 hoursPass, with nothing to report on day one

The empty first report is the result worth keeping. The pipeline was working end to end; the metric it reads simply did not exist yet, and a reporter that had invented a number instead would have looked more successful and been wrong.

Security and Cost

Security β€” Controls at Every Layer

ControlImplementationWhy It Matters
Encryption at restAES-256 (SSE-S3) with bucket key enabledBucket key reduces KMS API calls if switching to SSE-KMS later
Public access blockedAll four public access block settings enabledPrevents accidental public exposure regardless of bucket policy or ACL
SQS source restrictionQueue policy restricts SendMessage to the specific bucket ARNNo other S3 bucket (or principal) can write events to this queue
IAM least privilegeobject_tagger: s3:GetObject, s3:PutObjectTagging on one bucket only; reporter: cloudwatch:GetMetricStatistics, sns:Publish onlyEach Lambda can only do exactly what it needs
OIDC authenticationGitHub Actions uses OIDC, no static AWS credentials storedNo long-lived keys to rotate or leak
DLQ visibilityCloudWatch alarm on DLQ depth > 0Silent tagging failures become visible alerts

Cost

All prices us-east-1, verified 2026-06-30. Check aws.amazon.com/s3/pricing/ for current rates.

ResourceRateNotes
S3 Standard storage$0.023/GB/monthStarting tier; IT moves objects out over time
S3 Standard-IA$0.0125/GB/monthlogs/ prefix after 30 days
S3 Glacier Instant Retrieval$0.004/GB/monthlogs/ after 90d, IT Archive after 90d
S3 Glacier Deep Archive$0.00099/GB/monthIT Deep Archive after 180d
IT monitoring fee$0.0025/1,000 objects/monthObjects <128KB exempt from monitoring (and never transition)
Lambda (2 functions)< $0.01/monthLow invocation count; well within free tier
SQS< $0.01/monthPay per request; negligible for test volumes
SNS (1 email/day)< $0.01/monthFirst 1,000 email notifications free/month
EventBridge< $0.01/monthScheduled rules are free; custom events at $1/million
Typical Savings From IT

AWS publishes data showing 67% average storage cost reduction for buckets with mixed hot/cold data once Intelligent-Tiering is active. For a 1 TB bucket: $23.55/month at Standard, $7.79/month with IT fully tiered = $15.76/month savings. IT monitoring fee on 1,000 objects: $0.0025. The break-even is near-instant for any bucket with meaningful data volume.

Troubleshooting and Lessons

Problem. The first apply created 24 of 25 resources, then failed with InvalidArgument: Unable to validate the following destination configurations on the bucket notification.
Root cause. AWS validates the SQS queue policy before it will accept a bucket notification. The storage module and the cost-automation module had no dependency between them, so Terraform applied them in parallel and the notification tried to write before the queue policy had propagated.
Resolution. depends_on = [module.cost_automation] on the storage module, which serialises the two. The second apply added the missing resource with no change to the code.
Lesson. This is invisible at plan time β€” the plan succeeds because the queue will exist by apply. A module-level depends_on is the fix; a sleep is a workaround that passes for the same reason the plan did.

Problem. After a successful aws sso login, every command still failed with "Credentials were refreshed, but the refreshed credentials are still expired."
Root cause. ~/.aws/credentials carried a [default] section header whose keys were all commented out. That file takes precedence over ~/.aws/config, so an empty section was enough to shadow the SSO profile entirely.
Resolution. Removed the section header, put the SSO configuration in the [default] profile in config, and cleared both caches.
Lesson. A section header shadows the other file even when every value under it is a comment. The header alone is the configuration.

Cleanup and Key Takeaways

Cleanup

Versioned Buckets Cannot Be Destroyed Directly

terraform destroy fails on a non-empty versioned bucket: every object version and delete marker must go first.

The repo's cleanup.sh, and the destroy workflow that calls it, empty the bucket before destroying it.

bash
# Empty the versioned bucket before HCP destroy
BUCKET=$(aws s3api list-buckets --query "Buckets[?contains(Name,'week-08-s3-storage')].Name" --output text --profile personal)
bash week-08-s3-intelligent-storage/scripts/cleanup.sh $BUCKET

# Then trigger destroy from HCP Terraform UI: week-08-dev β†’ Actions β†’ Start destroy plan

References

Key Takeaways

  1. Intelligent-Tiering and lifecycle are not either/or. Tiering for patterns you do not know, rules for the ones you do.
  2. The unglamorous rules save the most. Aborting incomplete multipart uploads and expiring noncurrent versions remove storage nobody knows they are paying for.
  3. Put a queue between S3 and Lambda. A direct trigger works at low volume; the queue gives buffering, retries and a dead-letter queue.
  4. S3 storage metrics lag about 24 hours. Anything reading them on day one reports zero, correctly.
  5. Some ordering only AWS knows about. S3 validates the queue policy before accepting a notification, which no plan can see.

Comments

How was your experience?
Your feedback helps improve this site.
PoorExcellent