📋 In This Post
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.
- Catches what budgets miss Anomaly detection catches relative spikes — a service costing 3× its normal amount — even when the absolute dollar value is small.
- 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.
- 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.
- Zero ongoing maintenance The ML model updates itself continuously. One-time setup, permanent benefit. And it’s completely free.
Cloud Services and Concepts
| Service | Purpose here | What it is |
|---|---|---|
| AWS Cost Anomaly Detection | Decides what counts as unusual, so no threshold has to be guessed | A free Cost Explorer feature that learns each service's normal spend pattern and raises an anomaly when actual cost departs from it. |
| Anomaly monitor | Watches every service in the account | The 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 subscription | Decides when you hear about it | The threshold and frequency attached to a monitor — here, immediate delivery for anything above $10 of absolute impact. |
| Amazon SNS | Two topics: one AWS writes to, one a human reads | A publish-and-subscribe topic. One message is fanned out to every subscriber — email, a queue, or a function. |
| AWS Lambda | Turns the raw anomaly into a readable email | Runs a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs. |
| HCP Terraform | Provisioning, with no static keys | HashiCorp'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
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.
Prerequisites
| Requirement | Why | How to check |
|---|---|---|
| Cost Explorer enabled on the account | Anomaly detection is part of it, and nothing can be created until it is switched on — a one-time action in the console | The Cost Management console shows cost data rather than an enable prompt |
| Billing data history | The detector learns a normal pattern before it can call anything abnormal, so a brand-new account has nothing to compare against | Expect no anomalies at all on the first days |
| An email address to subscribe | An SNS subscription stays 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, not PendingConfirmation |
| An HCP Terraform workspace with OIDC | Keeps credentials out of the repo; the workspace is VCS-connected, so destroy is driven from the HCP UI | The 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 Actions | HCP Terraform | |
|---|---|---|
| State storage | S3 bucket (you manage) | HCP manages it |
| State locking | DynamoDB table | Built-in |
| CI/CD | GitHub Actions workflow | HCP VCS-driven |
| AWS credentials | OIDC via GitHub Actions | OIDC via HCP workspace |
| Free tier | ~$0 | Free ≤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.
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\"}]}"
}
}]
}
Post-deploy: confirm the SNS subscription, check the monitor is ACTIVE, and invoke the formatter — the mail should arrive within 30 seconds.
Validation and Evidence
Each row traces to a figure here; the lab was destroyed in June 2026.
| Test | Expected | Actual | Status |
|---|---|---|---|
| The stack deploys | A clean apply from a VCS-connected workspace | Applied successfully on week-05-dev | Pass |
| The monitor exists and covers everything | A DIMENSIONAL monitor across all services | Present and monitoring all services | Pass |
| The subscription has the intended threshold | Immediate delivery above $10 of absolute impact | IMMEDIATE frequency, $10 absolute impact | Pass |
| Both topics exist and are separate | One topic AWS publishes to, one a person subscribes to | raw-anomaly and cost-alert both created | Pass |
| The formatter runs | A test invocation publishes to the formatted topic | Execution succeeded and published | Pass |
| A human gets something readable | Expected against actual spend, with a root cause | Email delivered showing expected versus actual with the breakdown | Pass |
| A real anomaly is detected end to end | AWS raises one by itself and the mail arrives | Not observed. The alert path was proved with a test invocation; no genuine anomaly occurred during the lab's lifetime | Not observed |
| Teardown | Everything removed | 12 resources destroyed, nothing left billing | Pass |
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_IDstored in HCP, GitHub, or anywhere else. - Workspace-scoped OIDC trust The IAM trust policy uses
StringLikewith the workspace name in thesubcondition. Only theweek-05-devworkspace can assume this role. - Lambda least-privilege IAM The execution role has exactly two permissions:
sns:Publishscoped 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.comcan 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
| Service | Pricing | Monthly Cost |
|---|---|---|
| Cost Anomaly Detection | Free | $0.00 |
| SNS (2 topics) | First 1M publishes/month free | $0.00 |
| Lambda | First 1M requests + 400K GB-s free | $0.00 |
| CloudWatch Logs | First 5GB/month free | $0.00 |
| HCP Terraform | Free ≤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
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
- Getting started with AWS Cost Anomaly Detection — monitor types, subscription frequencies, threshold expressions.
- Receiving Cost Anomaly Detection alerts using Amazon SNS — documents the
costalerts.amazonaws.comservice principal. - aws_ce_anomaly_monitor — DIMENSIONAL and CUSTOM monitor types.
- aws_ce_anomaly_subscription — threshold expression syntax and subscriber configuration.
- Dynamic Provider Credentials — AWS — OIDC trust setup between HCP and AWS.
- Full source code — week-05-cost-anomaly-detection
10. Key Takeaways
costalerts.amazonaws.comis 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