Home› Blog› Week 5 - Cost Anomaly Detection with AWS Cost Expl…
AWS Weekly Lab AWS Terraform

Week 5 - Cost Anomaly Detection with AWS Cost Explorer, SNS, and Lambda

AWS Platform Engineering Lab · Week 05 of 52
Building an ML-powered spend monitoring pipeline — no more surprise bill spikes. Managed end-to-end with HCP Terraform and OIDC dynamic credentials.

Lab Overview

1. The Challenge — Why Fixed Budget Alerts Aren’t Enough

Your EC2 spend is normally $80 a month. This week it is running at $200 — 150% above normal. Your total bill is $280, well under the $500 budget whose alert fires at $450. Have you been told?

The problem. A budget threshold answers "have I spent more than X", which you have to know the right X for in advance, per service. Tripling your EC2 bill passes that test silently. A NAT gateway left running overnight added $35 in data processing charges here and raised nothing, because the total stayed under budget.

The objective. Ask a different question — "is this unlike me" — using Cost Anomaly Detection, which models expected spend per service per day, and turn what it emits into an email a person can act on.

The outcome. The pipeline works. Two of the four things that went wrong failed completely silently, which is the theme of the week.

  1. Catches what budgets miss Anomaly detection catches relative spikes — a service costing 3× its normal amount — even when the absolute dollar value is small.
  2. Immediate alerts, not end-of-month surprises IMMEDIATE frequency means the alert fires as soon as the anomaly is confirmed — typically within minutes of the cost spike starting.
  3. Root cause in the alert The alert payload includes the specific service, region, usage type, and linked account. You know where to look before you open the console.
  4. Zero ongoing maintenance The ML model updates itself continuously. One-time setup, permanent benefit. And it’s completely free.

Cloud Services and Concepts

ServicePurpose hereWhat it is
AWS Cost Anomaly DetectionDecides what counts as unusual, so no threshold has to be guessedA free Cost Explorer feature that learns each service's normal spend pattern and raises an anomaly when actual cost departs from it.
Anomaly monitorWatches every service in the accountThe object that defines what is being watched. A DIMENSIONAL monitor covers all services; other types narrow it to linked accounts, tags or cost categories.
Alert subscriptionDecides when you hear about itThe threshold and frequency attached to a monitor — here, immediate delivery for anything above $10 of absolute impact.
Amazon SNSTwo topics: one AWS writes to, one a human readsA publish-and-subscribe topic. One message is fanned out to every subscriber — email, a queue, or a function.
AWS LambdaTurns the raw anomaly into a readable emailRuns a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs.
HCP TerraformProvisioning, with no static keysHashiCorp's hosted Terraform. It runs plans and applies on its own machines and keeps the state file, and it assumes an AWS role by OIDC so no static keys exist anywhere.

A budget alert answers "have I spent more than X", and you must know X in advance. Anomaly detection asks "is this unlike me".

3. Skills & Tools Required

AWS Services

  • AWS Cost Explorer & Cost Anomaly Detection
  • SNS (Simple Notification Service) — two-topic fan-out pattern
  • Lambda (Python 3.12)
  • IAM — least-privilege roles, OIDC federation
  • CloudWatch Logs

Infrastructure & Tooling

  • Terraform — modules, cloud {} backend block
  • HCP Terraform — VCS-driven workspaces, OIDC dynamic credentials
  • Python — boto3, json, os
  • GitHub — VCS trigger for HCP runs

Concepts to understand before starting

  • ML-based anomaly detection. The model needs 10+ days of data to build a reliable baseline. Don’t expect alerts on a fresh account immediately.
  • SNS fan-out pattern. Two topics: one receives raw JSON from AWS, the second delivers a formatted email. Lambda sits between them as a transformer.
  • OIDC federation. HCP Terraform authenticates to AWS using short-lived tokens — no static keys stored anywhere.
  • VCS-driven IaC. Push to GitHub → HCP plans automatically. Merge to main → HCP applies. No GitHub Actions Terraform steps needed.

Architecture and Workflow

aws AWS Cloud Detection Cost Explorer ML spend baseline 1 Cost Anomaly Monitor DIMENSIONAL / SERVICE threshold: $10 above expected Alerting SNS: raw-anomaly AWS publishes here 2 enricher adds service and delta 3 SNS: alerts email to a human 4 The raw notification is JSON with no service name in it, which is why the enricher exists at all.

The architecture uses two SNS topics by design. The raw-anomaly topic receives dense JSON from AWS — not human-readable. Lambda transforms it and publishes a formatted plain-text alert to the cost-alert topic, which delivers to email subscribers. This separation gives a clean extension point: add Slack, PagerDuty, or Teams as additional subscribers to the formatted topic later without touching the detection layer.

Cost Anomaly Monitor in AWS console
Cost Anomaly Monitor configured in AWS — DIMENSIONAL type monitoring all services

Prerequisites

RequirementWhyHow to check
Cost Explorer enabled on the accountAnomaly detection is part of it, and nothing can be created until it is switched on — a one-time action in the consoleThe Cost Management console shows cost data rather than an enable prompt
Billing data historyThe detector learns a normal pattern before it can call anything abnormal, so a brand-new account has nothing to compare againstExpect no anomalies at all on the first days
An email address to subscribeAn SNS subscription stays pending until the confirmation link is clicked, and an unconfirmed topic delivers nothing while reporting successaws sns list-subscriptions-by-topic shows an ARN, not PendingConfirmation
An HCP Terraform workspace with OIDCKeeps credentials out of the repo; the workspace is VCS-connected, so destroy is driven from the HCP UIThe run page shows an applied run against the committed configuration

Implementation

Step 1 — Create the AWS OIDC provider and IAM role

AWS has to trust HCP first. This is a one-time manual bootstrap.

Register app.terraform.io as an OIDC identity provider, then create the role HCP will assume:

AWS CLI — one-time bootstrap

aws iam create-open-id-connect-provider \
  --url https://app.terraform.io \
  --client-id-list aws.workload.identity \
  --thumbprint-list <thumbprint>

aws iam create-role \
  --role-name hcp-terraform-role \
  --assume-role-policy-document file://trust-policy.json

JSON — trust-policy.json (scoped to this workspace)

{ "Effect": "Allow",
  "Principal": { "Federated": "arn:aws:iam::<ACCOUNT_ID>:oidc-provider/app.terraform.io" },
  "Action": "sts:AssumeRoleWithWebIdentity",
  "Condition": { "StringLike": { "app.terraform.io:sub": "organization:katta:*" } } }

Gotcha — org slug is case-sensitive

The organisation slug in the OIDC sub claim is lowercase, whatever case the UI shows.

Step 2 — Set up HCP Terraform workspace

S3 Backend + GitHub ActionsHCP Terraform
State storageS3 bucket (you manage)HCP manages it
State lockingDynamoDB tableBuilt-in
CI/CDGitHub Actions workflowHCP VCS-driven
AWS credentialsOIDC via GitHub ActionsOIDC via HCP workspace
Free tier~$0Free ≤500 resources

Create the workspace with the Version Control workflow and point it at the environment directory.

Step 3 — Terraform backend and module composition

HCL — terraform/environments/dev/main.tf

terraform {
  cloud {
    organization = "Katta"
    workspaces { name = "week-05-dev" }
  }
}

Step 4 — SNS topic policy (the part everyone gets wrong)

Important

The publishing principal is costalerts.amazonaws.com, not budgets.amazonaws.com — see Troubleshooting.

HCL — SNS topic policy

resource "aws_sns_topic_policy" "raw_anomaly" {
  arn = aws_sns_topic.raw_anomaly.arn

  policy = jsonencode({
    Statement = [{
      Principal = { Service = "costalerts.amazonaws.com" }
      Action    = "SNS:Publish"
      Resource  = aws_sns_topic.raw_anomaly.arn
    }]
  })
}

Step 5 — Cost Anomaly Monitor and Subscription

HCL — modules/cost_anomaly/main.tf

resource "aws_ce_anomaly_monitor" "this" {
  name              = "${var.project}-${var.environment}-monitor"
  monitor_type      = "DIMENSIONAL"
  monitor_dimension = "SERVICE"
}

resource "aws_ce_anomaly_subscription" "this" {
  frequency = "IMMEDIATE"
  ...  # $10 absolute-impact threshold, raw-anomaly topic
}

Step 6 — Lambda alert formatter

The function turns the raw anomaly JSON into a plain-text email: service, expected against actual, and the root cause.

Python — lambda/cost_alerter/handler.py

def format_alert(payload):
    impact = payload.get("impact", {})
    expected = impact.get("totalExpectedSpend", 0.0)
    actual   = impact.get("totalActualSpend", 0.0)
    ...  # service, dates and root causes, then sns.publish()

Step 7 — Configure OIDC dynamic credentials

Two workspace variables replace the whole credential setup, pointing at the role from step 1.

HCP Workspace Environment Variables

TFC_AWS_PROVIDER_AUTH  = true
TFC_AWS_RUN_ROLE_ARN   = arn:aws:iam::<ACCOUNT_ID>:role/hcp-terraform-role

Step 8 — Push to GitHub and apply via HCP

A push queues a plan automatically, but a VCS-connected workspace refuses terraform apply from any CLI — the run page is where an apply or a destroy is confirmed.

HCP Terraform run applied
HCP Terraform workspace week-05-dev — VCS-connected run, applied successfully
SNS topics in AWS console
Both SNS topics created — raw-anomaly (AWS-to-Lambda) and cost-alert (Lambda-to-email)
Cost Anomaly Detection alert subscription
Alert subscription — IMMEDIATE frequency, $10 absolute impact threshold

Step 9 — Test immediately after deploy

Don’t wait for a real anomaly. Use the Lambda test console with a mock payload to verify the full pipeline:

JSON — Lambda test event

{
  "Records": [{
    "Sns": {
      "Message": "{\"dimensionValue\":\"Amazon EC2\",
                   \"impact\":{\"totalActualSpend\":22.50,
                               \"totalExpectedSpend\":10.00,
                               \"totalImpact\":12.50},
                   \"rootCauses\":[{\"service\":\"Amazon EC2\",
                                    \"region\":\"us-east-1\",
                                    \"usageType\":\"BoxUsage:t3.medium\"}]}"
    }
  }]
}
Lambda test execution succeeded
Lambda test — execution succeeded, alert published to the formatted-alert topic

Post-deploy: confirm the SNS subscription, check the monitor is ACTIVE, and invoke the formatter — the mail should arrive within 30 seconds.

Formatted cost anomaly email
Formatted alert email — expected vs. actual spend with root cause breakdown

Validation and Evidence

Each row traces to a figure here; the lab was destroyed in June 2026.

TestExpectedActualStatus
The stack deploysA clean apply from a VCS-connected workspaceApplied successfully on week-05-devPass
The monitor exists and covers everythingA DIMENSIONAL monitor across all servicesPresent and monitoring all servicesPass
The subscription has the intended thresholdImmediate delivery above $10 of absolute impactIMMEDIATE frequency, $10 absolute impactPass
Both topics exist and are separateOne topic AWS publishes to, one a person subscribes toraw-anomaly and cost-alert both createdPass
The formatter runsA test invocation publishes to the formatted topicExecution succeeded and publishedPass
A human gets something readableExpected against actual spend, with a root causeEmail delivered showing expected versus actual with the breakdownPass
A real anomaly is detected end to endAWS raises one by itself and the mail arrivesNot observed. The alert path was proved with a test invocation; no genuine anomaly occurred during the lab's lifetimeNot observed
TeardownEverything removed12 resources destroyed, nothing left billingPass

Security and Cost

7. Security Best Practices

  • No static AWS credentials anywhere HCP Terraform authenticates via OIDC, minting short-lived tokens scoped to the workspace. No AWS_ACCESS_KEY_ID stored in HCP, GitHub, or anywhere else.
  • Workspace-scoped OIDC trust The IAM trust policy uses StringLike with the workspace name in the sub condition. Only the week-05-dev workspace can assume this role.
  • Lambda least-privilege IAM The execution role has exactly two permissions: sns:Publish scoped to the formatted alert topic ARN, and CloudWatch Logs write access scoped to its own log group.
  • SNS topic policy scoped to service principal Only costalerts.amazonaws.com can publish to the raw-anomaly topic. No IAM user, cross-account entity, or other AWS service can inject fake anomaly payloads.
  • CloudWatch log retention set explicitly Without an explicit retention_in_days, log groups retain logs indefinitely — an unbounded cost. This Lambda’s log group is set to 14 days.

8. Cost & Cleanup

ServicePricingMonthly Cost
Cost Anomaly DetectionFree$0.00
SNS (2 topics)First 1M publishes/month free$0.00
LambdaFirst 1M requests + 400K GB-s free$0.00
CloudWatch LogsFirst 5GB/month free$0.00
HCP TerraformFree ≤500 managed resources$0.00
Total$0.00

Cleanup must go through HCP, not GitHub Actions

The workspace is VCS-connected, so apply and destroy are confirmed in the HCP UI rather than from any CLI.

Cleanup — via HCP Terraform UI

Workspace (week-05-dev) → Actions → Start new run → Plan and destroy
→ review the plan → Confirm & Apply
HCP Terraform destroy run completed
Destroy run triggered from the HCP UI — 12 resources destroyed, $0 remaining

Troubleshooting and Lessons

Problem. The monitor and the subscription were both created and no alert ever fired. No error in CloudWatch, nothing in the console.
Root cause. The SNS topic policy named budgets.amazonaws.com as the principal. Cost Anomaly Detection publishes as costalerts.amazonaws.com, and AWS drops a refused publish silently.
Resolution. Name the right principal.
Lesson. A topic policy that refuses a publisher fails closed and quietly. The only evidence is the absence of messages, which looks exactly like "nothing has happened yet".

Problem. Days passed with no real alert, even while running charges up deliberately.
Root cause. Not a fault. The detector needs enough spend history to build a baseline before it can call anything anomalous, and a new monitor has none.
Resolution. Prove the delivery path with a test event, and wait for the baseline for the detection itself.
Lesson. With anything that learns normal first, "no alert" is the expected state for a while. Test the pipeline and the detector separately, because only one of them can be tested today.

Problem. The function ran successfully and no email arrived.
Root cause. The subscription was still in PendingConfirmation. SNS does not deliver to an unconfirmed endpoint, and does not treat that as an error.
Resolution. Click the confirmation link.
Lesson. This is the second silent failure in the same build, both on the delivery side. Assert on the subscription's state, not on its existence.

Problem. Every plan failed with No Terraform configuration files found in working directory, for a directory that was plainly in the repo.
Root cause. Partly established. The HCP GitHub App's repository access was scoped to a different repository, which explains the clone having nothing in it. Granting access did not on its own fix it.
Resolution. Enabling "Include submodules on clone" is what broke the cycle. The repository has no submodules, so why that mattered is unconfirmed, and it is recorded here as what worked rather than as an explanation.
Lesson. A VCS-connected workspace also refuses terraform apply from the CLI entirely — once VCS is the source of truth, the run page is the only place an apply or a destroy happens.

Cleanup and Key Takeaways

9. References

10. Key Takeaways

  • costalerts.amazonaws.com is the SNS publisher principal for Cost Anomaly Detection — wrong principal causes silent failure with no error.
  • The ML baseline needs 24–48 hours on a new monitor. Test with Lambda test events immediately after deploy.
  • Two topics, not one. A raw topic for AWS to publish to and a formatted one for people, so Slack or PagerDuty can be added without touching detection.
  • HCP dynamic credentials eliminate static AWS keys entirely. 15 minutes of setup, zero ongoing rotation burden.
  • Confirm the SNS email subscription before testing. Messages to unconfirmed subscriptions are silently dropped.
  • VCS-connected workspaces fail in layered ways. GitHub App repo access, OIDC slug case and stale config ingestion all surface as the same empty-directory error.
  • Cost Anomaly Detection is completely free. The only reason not to have it in every AWS account is not knowing it exists.

Comments

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