π In This Post
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
| Service | Purpose here | What it is |
|---|---|---|
| Amazon S3 | The bucket everything in this lab is about | Object 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-Tiering | Moves objects between tiers without anyone deciding | A 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 rules | Transitions by age, and the housekeeping | Rules 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 Lambda | Tags objects on upload, and reports the bill | Runs a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs. |
| Amazon EventBridge | Runs the cost report once a day | An event bus. Services and your own code publish events to it, and rules decide which events reach which targets β including on a schedule. |
| Amazon SNS | Delivers the daily report by email | A publish-and-subscribe topic. One message is fanned out to every subscriber β email, a queue, or a function. |
| Amazon SQS | The dead-letter queue behind the tagger | A queue that holds messages until something collects them, including the ones a function failed to process. |
| Amazon CloudWatch | Where the storage metrics come from | AWS'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:
| Class | Use When | Price (us-east-1, July 2026) |
|---|---|---|
| Standard | Frequent access, unknown access pattern | $0.023/GB/month |
| Standard-IA | Infrequent access, retrieval in milliseconds | $0.0125/GB/month |
| Glacier Instant Retrieval | Archive, retrieval in milliseconds | $0.004/GB/month |
| Glacier Deep Archive | Long-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.
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
| Requirement | Why | How to check |
|---|---|---|
| An HCP Terraform workspace with OIDC into an AWS role | Keeps credentials out of the repo and out of CI | The workspace assumes the role on each run; no static keys exist anywhere |
| An email address you can read during the apply | An SNS subscription is pending until the confirmation link is clicked, and an unconfirmed topic delivers nothing while reporting success | aws sns list-subscriptions-by-topic shows an ARN rather than PendingConfirmation |
| A day of patience before judging the report | S3 storage metrics in CloudWatch are published roughly daily, so the first report is legitimately empty β this is not a bug in the reporter | The first report says so; the second has numbers |
| Terraform with the AWS provider | Everything here is declared; nothing is clicked | terraform 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.
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.
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.
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):
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:
Step 7 β Verify S3 Configuration in the Console
After the apply, the bucket, its tiering configuration and its lifecycle rules:
Step 9 β Test Object Tagging
A test object in the logs/ prefix, tagged by the pipeline:
echo "test log entry" | aws s3 cp - s3://$BUCKET/logs/app/2026-07-02.log --profile personal
content-type: logs, upload-date: 2026-07-03Step 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.
aws lambda invoke \ --function-name week-08-s3-storage-dev-storage-reporter \ --invocation-type RequestResponse \ out.json --profile personal && cat out.json
The next morning the schedule fired on its own and delivered the first real report:
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.
| Test | Expected | Actual | Status |
|---|---|---|---|
| The platform deploys | 25 resources | 24 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 code | Pass on retry |
| The bucket is hardened | Versioning on, SSE-S3 encryption, public access fully blocked | All three confirmed in the console | Pass |
| Intelligent-Tiering is configured | Archive Instant at 90 days, Deep Archive at 180, bucket-wide | Applied bucket-wide as declared | Pass |
| Lifecycle rules exist | Three: 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 30 | All three present | Pass |
| Objects are tagged on upload | content-type and upload-date applied by the tagger | content-type: logs, upload-date: 2026-07-03 | Pass |
| The tagger has no failures | An empty dead-letter queue | DLQ message count zero | Pass |
| The daily report is delivered | An email, on a schedule, with the bucket's size | Delivered. StatusCode 200, total_bytes 0 β the report correctly said there was no data yet, because S3 storage metrics lag about 24 hours | Pass, 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
| Control | Implementation | Why It Matters |
|---|---|---|
| Encryption at rest | AES-256 (SSE-S3) with bucket key enabled | Bucket key reduces KMS API calls if switching to SSE-KMS later |
| Public access blocked | All four public access block settings enabled | Prevents accidental public exposure regardless of bucket policy or ACL |
| SQS source restriction | Queue policy restricts SendMessage to the specific bucket ARN | No other S3 bucket (or principal) can write events to this queue |
| IAM least privilege | object_tagger: s3:GetObject, s3:PutObjectTagging on one bucket only; reporter: cloudwatch:GetMetricStatistics, sns:Publish only | Each Lambda can only do exactly what it needs |
| OIDC authentication | GitHub Actions uses OIDC, no static AWS credentials stored | No long-lived keys to rotate or leak |
| DLQ visibility | CloudWatch alarm on DLQ depth > 0 | Silent tagging failures become visible alerts |
Cost
All prices us-east-1, verified 2026-06-30. Check aws.amazon.com/s3/pricing/ for current rates.
| Resource | Rate | Notes |
|---|---|---|
| S3 Standard storage | $0.023/GB/month | Starting tier; IT moves objects out over time |
| S3 Standard-IA | $0.0125/GB/month | logs/ prefix after 30 days |
| S3 Glacier Instant Retrieval | $0.004/GB/month | logs/ after 90d, IT Archive after 90d |
| S3 Glacier Deep Archive | $0.00099/GB/month | IT Deep Archive after 180d |
| IT monitoring fee | $0.0025/1,000 objects/month | Objects <128KB exempt from monitoring (and never transition) |
| Lambda (2 functions) | < $0.01/month | Low invocation count; well within free tier |
| SQS | < $0.01/month | Pay per request; negligible for test volumes |
| SNS (1 email/day) | < $0.01/month | First 1,000 email notifications free/month |
| EventBridge | < $0.01/month | Scheduled rules are free; custom events at $1/million |
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
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.
# 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
- Full lab guide on GitHub β prerequisites, Terraform, commands, validation and cleanup.
- AWS Docs: S3 Intelligent-Tiering
- AWS Docs: S3 Lifecycle Management
- S3 Pricing (us-east-1, current)
- Terraform: aws_s3_bucket_intelligent_tiering_configuration
- Terraform: aws_s3_bucket_lifecycle_configuration
- AWS Docs: S3 Event Notifications
- Source Code: week-08-s3-intelligent-storage
Key Takeaways
- Intelligent-Tiering and lifecycle are not either/or. Tiering for patterns you do not know, rules for the ones you do.
- The unglamorous rules save the most. Aborting incomplete multipart uploads and expiring noncurrent versions remove storage nobody knows they are paying for.
- Put a queue between S3 and Lambda. A direct trigger works at low volume; the queue gives buffering, retries and a dead-letter queue.
- S3 storage metrics lag about 24 hours. Anything reading them on day one reports zero, correctly.
- Some ordering only AWS knows about. S3 validates the queue policy before accepting a notification, which no plan can see.
Comments