Cost Anomaly Response Automator
What this skill does
Designs automated AWS cost-anomaly response workflows that move a
spend spike from detection to actionable notification (or scoped
remediation) without human latency. Supports five detection sources
(Cost Anomaly Detection, AWS Budgets, Cost Explorer anomaly view, CUR
Athena analysis, Amazon Q cost-optimization recommendations), five
response patterns (notify, tag, budget-action, CUR top-spenders
drill-down, full-playbook), and three orchestration surfaces
(EventBridge + Lambda, EventBridge + Step Functions, Budgets native
actions).
The verdict is binary: AUTOMATED when the workflow is complete,
includes dry-run, has scoped IAM, lands an approval gate before any
resource-stopping action, and writes a CloudTrail-auditable record;
MANUAL_STEP_REQUIRED when any guardrail or coverage gate fails,
with the specific gap enumerated in FINDINGS.
STRICT output contract
Every invocation MUST emit exactly one design or validation block in
this shape — no prose before, no commentary after:
DETECTION_SOURCE: <cad | budgets | ce-anomaly | cur | q-recommendations>
RESPONSE_SCOPE: <notify | tag | budget-action | cur-analysis | full-playbook>
VERDICT: AUTOMATED | MANUAL_STEP_REQUIRED
WORKFLOW:
Detection: <monitor or budget name + ARN>
EventBridge rule: <name or "n/a (Budgets native)">
Lambda / Step Functions: <arn or name>
Budgets action: <action name or "none">
SNS topic: <arn>
Notification target: <Slack / Teams / email / PagerDuty>
GUARDRAILS:
- [PASS|FAIL] Dry-run mode implemented
- [PASS|FAIL] Approval gate before resource-stopping action
- [PASS|FAIL] Scoped IAM (least privilege)
- [PASS|FAIL] Idempotency check on Lambda
- [PASS|FAIL] Kill-switch (Parameter Store or EventBridge disable)
AUDIT:
- [PASS|FAIL] CloudTrail covers the account
- [PASS|FAIL] Notification includes anomaly ID + impact USD
- [PASS|FAIL] Budgets action execution logged
FINDINGS:
- [INFO|WARN|HIGH|CRITICAL] <observation>
REMEDIATION:
1. <specific action with CLI command>
2. <verification command>
A block missing VERDICT, GUARDRAILS, or REMEDIATION is a contract
violation — re-emit the full block.
Quick navigation
Mindset
One-line takeaway: spend-response automation trades blast radius
for speed — a fast wrong action (stopping every EC2 instance in prod)
is more expensive than the anomaly you are trying to contain. The
workflow's job is to surface the spike; the guardrail's job is to
ensure the automation does not amplify the damage.
Three facts shape every cost-anomaly automation decision:
- Notification is reversible; remediation is not. Posting a Slack
message is reversible. Attaching an IAM deny policy is reversible.
Stopping an EC2 instance causes an outage. Terminating is
irreversible. Default to notify + tag; require a human-approval gate
before any availability-affecting action.
- CAD detects anomalies on a 6-24 hour lag, not in real time. CAD
evaluates daily or weekly cadences; the spike at 09:00 UTC likely
started 12-24 hours ago. Budgets are similar. Near-real-time
detection requires CloudWatch billing alarms (4h poll) or
CUR/Athena on a schedule.
- The kill-switch is more important than the trigger. A workflow
that fires on every CAD anomaly above USD 100 is fine if scoped.
Without a kill-switch, a misconfigured monitor, load test, or
marketing launch can trigger dozens of actions per hour.
Pre-flight: spec gate (run before generation)
| Attribute |
Required |
Effect on plan |
detection_source |
YES |
Determines the EventBridge source or Budgets native trigger |
response_scope |
YES |
Determines the actions (notify only, full-playbook, etc.) |
severity_threshold |
Recommended |
USD impact (CAD) or % of budget (Budgets). Default 100 USD / 80%. |
target_regions |
Recommended |
Cost is global; Budgets actions are per-region. |
approval_required |
RECOMMENDED |
Required true if response_scope includes budget-action with stop. |
existing_workflow |
For validation |
Skip generation; run guardrail + audit gates. |
If the spec is incomplete, emit:
DETECTION_SOURCE: <unknown>
RESPONSE_SCOPE: <unknown>
VERDICT: MANUAL_STEP_REQUIRED
REASON: Spec is missing required fields (<list>).
REQUIRED:
- detection_source (cad | budgets | ce-anomaly | cur | q-recommendations)
- response_scope (notify | tag | budget-action | cur-analysis | full-playbook)
REMEDIATION: Provide both fields. Example: "notify Slack on any CAD
anomaly above USD 500" maps to detection_source=cad,
response_scope=notify, severity_threshold=500.
Live-account pre-flight commands (CAD enabled, CUR exists, SNS topic, Lambda role scope, Budgets enabled): references/diagnostic-commands.md.
Decision tree — orchestration selection
Apply top-to-bottom. First matching rule wins.
START
|
+-- notify only? -------------> EventBridge rule + Lambda
| (Lambda formats and posts to Slack/Teams/email)
+-- tag resources? -----------> EventBridge rule + Lambda
| (Lambda calls resourcegroupstaggingapi:TagResources)
+-- budget-action? -----------> AWS Budgets native action
| (IAM policy attach, EC2 stop, SNS notify)
+-- cur-analysis? ------------> EventBridge schedule + Lambda/Athena
| (Athena top-spenders, post summary to Slack)
+-- full-playbook? -----------> EventBridge rule + Step Functions
| (notify -> tag -> wait for approval -> action)
+-- q-recommendations? -------> EventBridge schedule + Lambda
| (poll Q, dedupe, post to Slack)
+-- (unrecognized) -----------> MANUAL_STEP_REQUIRED with mapping hint
Orchestration surface selection:
- Lambda-only: single-action responses <15 min (Lambda max).
Cheapest and simplest.
- Step Functions: multi-phase, parallel, or approval-gated
responses. Required when a destructive action needs an approval gate.
- Budgets native actions: IAM policy attach and EC2 stop triggered
directly by budget breach. No EventBridge wiring; limited to a
single threshold and a single action per budget.
- Athena scheduled query: CUR top-spenders on a schedule. Athena
writes to S3; a Lambda posts the summary to Slack.
Step 0: Expert knowledge — non-obvious cost behaviors
Full catalog (CAD daily/weekly lag, TotalImpact semantics, Budgets 8-12h evaluation, calendar-month reset, single-threshold actions, IAM-policy vs EC2-stop targeting, CUR 8-24h latency, Glue partitions, SNS confirmation, webhook storage, EventBridge gaps, Q scoping, COH dedupe, monitor types): references/advanced-patterns.md.
Detection sources
AWS Cost Anomaly Detection (CAD)
Monitor and subscription CLI (list monitors, SERVICE and LINKED_ACCOUNT monitors, SNS-wired anomaly subscription, get-anomalies): references/cad-budgets-action-catalog.md.
AWS Budgets
Budget and action CLI (create-budget, 80% SNS notify, 100% IAM deny AUTOMATIC, 120% EC2 stop MANUAL): references/cad-budgets-action-catalog.md.
Cost Explorer anomaly view
Cost Explorer surfaces anomalies in the console under "Cost Anomaly
Detection". The same data is available via aws ce get-anomalies. CE
is the visualization; CAD is the engine. Use get-anomalies
programmatically and surface in your own dashboard or Slack via
Lambda.
CUR analysis automation
CUR verify + top-spenders Athena SQL + EventBridge daily schedule CLI: references/cad-budgets-action-catalog.md.
Amazon Q cost-optimization recommendations
Cost Optimization Hub get-recommendations CLI + scheduled Lambda poll/dedupe pattern: references/cad-budgets-action-catalog.md.
Response patterns
1. Notify (Slack / Teams / email / PagerDuty)
import json, urllib.request, os
def lambda_handler(event, context):
webhook = os.environ['SLACK_WEBHOOK_URL'] # from Parameter Store
record = json.loads(event['Records'][0]['Sns']['Message'])
impact = record.get('Impact', {}).get('TotalImpact', 'unknown')
service = record.get('Impact', {}).get('Services', [{}])[0].get('ServiceName', 'unknown')
msg = {'text': (
f":moneybag: *Cost Anomaly*\nImpact: ${impact}\n"
f"Service: {service}\nAnomaly ID: {record.get('AnomalyId','unknown')}\n"
f"Account: {record.get('AccountId','unknown')}")}
urllib.request.urlopen(urllib.request.Request(
webhook, json.dumps(msg).encode(), {'Content-Type': 'application/json'}))
2. Tag suspect resources
import boto3, json, os
tag_api = boto3.client('resourcegroupstaggingapi')
def lambda_handler(event, context):
record = json.loads(event['Records'][0]['Sns']['Message'])
anomaly_id = record['AnomalyId']
resources = json.loads(os.environ['SUSPECT_RESOURCES']) # populated by Step Functions CUR query
tag_api.tag_resources(ResourceARNList=resources,
Tags={'CostAnomaly': anomaly_id, 'Investigate': 'true'})
3. Budgets native actions
Budgets actions run in the Budgets service — no EventBridge or Lambda
for the action itself. Use APPLY_IAM_POLICY for soft containment
(deny new resource creation) and RUN_SSM_DOCUMENTS with
STOP_EC2_INSTANCES for hard containment.
4. CUR top-spenders drill-down
import boto3
athena = boto3.client('athena')
def lambda_handler(event, context):
query = '''SELECT lineitem_product_servicename, resource_id,
SUM(lineitem_unblendedcost) AS spend
FROM "cur"."cur_table"
WHERE year='{y}' AND month='{m}'
GROUP BY 1, 2 HAVING SUM(lineitem_unblendedcost) > 100
ORDER BY spend DESC LIMIT 20'''.format(y='2026', m='08')
return {'QueryExecutionId': athena.start_query_execution(
QueryString=query, QueryExecutionContext={'Database': 'cur'},
ResultConfiguration={'OutputLocation': 's3://cur-athena-results-us-east-1/'}
)['QueryExecutionId']}
5. Full-playbook (Step Functions)
Full state-machine JSON (kill-switch check -> notify -> tag -> SQS task-token approval -> optional Budgets action -> close): references/advanced-patterns.md.
Step Functions orchestration
For full-playbook cost response (multi-phase, approval-gated), use
Step Functions. The state machine above orchestrates the canonical
pattern: kill-switch check -> notify -> tag -> wait for approval ->
optional action -> close.
| Pattern |
Use when |
Trade-off |
Wait state with fixed duration |
One-shot timer ("wait 1h, then auto-stop") |
Stays "Running"; clutters dashboard |
Task with waitForTaskToken |
Human callback via SQS/CLI |
Pauses cleanly; resumes on callback |
Always prefer task-token callback for human approval gates.
Guardrails (MANDATORY)
Every cost-anomaly automation MUST include:
- A kill-switch checked BEFORE any action. Parameter Store
(
/cost/kill-switch), Lambda guard, or EventBridge rule disable.
- Dry-run mode for the first deployment. Set the workflow to
notify-only for 1-2 weeks; promote to actions after.
- An approval gate before any resource-stopping action. Use Step
Functions
Task with waitForTaskToken and an SQS queue.
- Scoped IAM roles.
ce:GetAnomalies (read), sns:Publish on
the topic, resourcegroupstaggingapi:TagResources on specific
ARNs — NOT *:* on *.
- Idempotency. Handle multiple triggers for the same anomaly.
Use
AnomalyId as the dedupe key (DynamoDB or Parameter Store).
- No destructive actions without explicit approval. Notification,
tagging, IAM deny (reversible) are allowed without approval. EC2
stop/terminate, resource deletion require an approval gate.
# Kill-switch pattern
aws ssm put-parameter --name /cost/kill-switch --value "enabled" --type String
aws ssm put-parameter --name /cost/kill-switch --value "disabled" \
--type String --overwrite # one-command disable
Output format — worked examples
Worked example — AUTOMATED full-playbook
DETECTION_SOURCE: cad
RESPONSE_SCOPE: full-playbook
VERDICT: AUTOMATED
WORKFLOW:
Detection: ec2-spend-monitor (arn:aws:ce::111122223333:anomalymonitor/abc-123)
Anomaly subscription: prod-cost-anomaly-sub (threshold USD 100, daily)
SNS topic: arn:aws:sns:us-east-1:111122223333:cost-anomaly-alerts
Lambda: cost-notify-slack, cost-tag-resources, cost-budget-action
Step Functions: arn:aws:states:us-east-1:111122223333:stateMachine:cost-full-playbook
Budgets action: monthly-ec2-budget (IAM deny 100%, EC2 stop 120%)
Kill-switch: Parameter Store /cost/kill-switch
GUARDRAILS:
- [PASS] Dry-run 2026-07-15 to 2026-07-29 (14 days, notify-only)
- [PASS] Approval gate via SQS task token before EC2 stop
- [PASS] Lambda role scoped to ce:GetAnomalies, sns:Publish,
resourcegroupstaggingapi:TagResources, budgets:ExecuteBudgetAction
- [PASS] Idempotency: DynamoDB cost-anomaly-dedupe keyed by AnomalyId
- [PASS] Kill-switch checked first in state machine
AUDIT:
- [PASS] CloudTrail org trail covers 111122223333
- [PASS] Slack notification includes AnomalyId, Impact USD, Service
- [PASS] Budgets action execution logged; tagged CostAnomaly=<AnomalyId>
FINDINGS:
- [INFO] SNS subscription confirmed; CAD evaluates daily (6-24h latency)
- [WARN] CUR/Athena top-spenders query runs on a 12h delay
REMEDIATION: aws cloudformation deploy --stack-name prod-cost-workflow \
--template-file cost-workflow.yaml --capabilities CAPABILITY_NAMED_IAM
Worked example — MANUAL_STEP_REQUIRED (missing approval gate)
Full MANUAL_STEP_REQUIRED example (Budgets EC2 stop AUTOMATIC at 120%, no approval gate): references/worked-examples.md.
NEVER (these things)
NEVER deploy a budget EC2-stop action without an approval gate.
Budgets native RUN_SSM_DOCUMENTS with STOP_EC2_INSTANCES and
ApprovalModel=AUTOMATIC stops instances the moment the threshold
crosses — including during a billing-cycle lag when actual spend has
already returned to normal. The stop causes an outage that costs
more than the anomaly. Use ApprovalModel=MANUAL or wire the stop
behind a Step Functions task-token approval gate.
NEVER grant the cost-response Lambda ec2:* or iam:* on *.
Scope to ce:GetAnomalies, resourcegroupstaggingapi:TagResources
on specific ARNs, budgets:ExecuteBudgetAction on specific budget
ARNs. A Lambda that can stop any EC2 instance or attach any IAM
policy is a privilege-escalation target.
NEVER assume SNS notifications will be delivered. SNS requires
endpoint confirmation. An unconfirmed subscription silently drops
messages. Always send a test message after creating the topic.
NEVER hardcode Slack/Teams webhook URLs in Lambda code. Store
in Parameter Store (free, encrypted by default) or Secrets Manager
(paid, KMS-encrypted, rotation support). A hardcoded URL leaked via
CloudTrail GetFunctionConfiguration lets anyone post to your
Slack channel.
NEVER skip the dry-run window. A workflow deployed straight to
live without a 1-2 week dry-run (notify-only) period will misfire
on the first real anomaly — wrong Slack channel, malformed
notification, idempotency miss, or scoped-IAM gap.
NEVER terminate EC2 instances from cost automation. Stopping is
reversible; terminating destroys the resource and its EBS volumes.
Terminate decisions require human judgment and are out of scope.
NEVER rely on Budgets for real-time detection. Budgets evaluates
every 8-12 hours; CAD evaluates daily/weekly. For sub-hour
detection, use CloudWatch billing alarms (4h poll) or CUR Athena.
NEVER attach an IAM deny-all policy to a role the Lambda or Step
Functions execution role assumes. The deny-all cascades and blocks
the workflow itself. Apply deny-all only to user-serving roles.
NEVER use ApprovalModel=AUTOMATIC for Budgets actions with
RUN_SSM_DOCUMENTS. Use MANUAL for EC2/RDS stop. Reserve
AUTOMATIC for APPLY_IAM_POLICY (reversible) and
SNS_NOTIFICATION.
NEVER forget to dedupe Amazon Q / Cost Optimization Hub
recommendations by recommendationId. A daily Lambda poll without
dedupe reposts the same recommendation daily, creating Slack noise
that trains the team to ignore the channel.
Expert heuristic — the 60-second triage
When handed a cost-response design request, run this 60-second triage
before drafting the workflow:
- Identify the detection source. CAD (anomaly ML), Budgets
(threshold), CUR/Athena (top-spenders), or Q (recommendations).
- Identify the response severity. Notify-only (reversible, no
approval needed) vs resource-affecting (approval gate required).
- Identify the latency expectation. CAD = 6-24h. Budgets = 8-12h.
CUR/Athena = schedule-dependent. Set expectations explicitly.
- Identify the kill-switch. Parameter Store, EventBridge disable,
or Lambda guard. No kill-switch = MANUAL_STEP_REQUIRED.
- Identify the dry-run plan. Ship with a 1-2 week dry-run
(notify-only) before going live with actions.
If any of the five is missing or unclear, emit MANUAL_STEP_REQUIRED.
Pre-flight safety checks (run before any deploy)
- MANDATORY CONFIRMATION GATE. Before any state-changing operation
(
cloudformation deploy, events put-rule, budgets put-budget-action, lambda create-function), emit and await
operator approval.
- Dry-run first. Deploy with
response_scope=notify for 1-2 weeks
before promoting to budget-action or full-playbook.
- Validate the kill-switch. Set
/cost/kill-switch to "disabled"
and verify a test anomaly does NOT trigger the action.
- Verify Slack/Teams webhook. Send a test message before relying
on it. Capture existing Budgets configuration before deploying new
actions.
- Bulk operation safety limit. Slice multi-account deploys into
batches of at most 3 accounts; emit per-account CONFIRM per batch.
Edge-case handling
Edge-case catalog (deleted resource, cross-account rollup, planned spike, CUR schema change, stale instance list): references/advanced-patterns.md.
Recent AWS features (2024-2026)
What changed in 24 months (CAD ML impact, Budgets SSM documents, Cost Optimization Hub, Amazon Q, CUR 2.0 Parquet, calendar-month reset): references/advanced-patterns.md.
References (load on demand)
- Worked examples - MANUAL_STEP_REQUIRED worked example: Budgets EC2 stop at 120% with no approval gate
- Diagnostic commands - live-account pre-flight commands (CAD monitors, CUR, SNS, Lambda role, Budgets)
- Advanced patterns - Step 0 non-obvious cost behaviors, full-playbook Step Functions state machine, edge-case handling, recent AWS features
- CAD/Budgets/Athena action catalog - detection-source CLI (CAD monitors/subscriptions, Budgets + native actions, CUR top-spenders query, Cost Optimization Hub polling)
Domain
AWS CloudOps / FinOps — cost anomaly response automation.
AWS documentation
1---2name: cost-anomaly-response-automator3description: 'Designs automated AWS cost-anomaly detection and response workflows across AWS Cost Anomaly Detection (CAD) monitors (service, linked account, daily/weekly/monthly cadence), anomaly subscriptions (SNS), automated response patterns (EventBridge to Lambda: notify Slack or Teams, tag suspect resources, trigger a Budgets action), AWS Budgets cost-budget auto-actions (IAM policy attach, EC2 stop), Cost Explorer anomaly views, and CUR (Cost and Usage Report) analysis automation (Athena top-spenders queries). Layers in the latest: CAD with ML impact evaluation, Amazon Q cost-optimization recommendations, and Budgets advanced actions. Enforces guardrails: dry-run first, human-approval gate for any resource-stopping action, scoped IAM, idempotency, full CloudTrail audit. Emits AUTOMATED with response plan or MANUAL_STEP_REQUIRED with the specific gap. Use when wiring Cost Anomaly Detection or Budgets to a notification or remediation pipeline.'4license: Apache-2.05compatibility: Agent runtime that reads SKILL.md (Claude Code, Cursor, Windsurf, Codex, Gemini). No AWS CLI required for offline plan authoring. Live deployment uses aws ce create-anomaly-monitor, create-anomaly- subscription, get-anomalies; aws budgets create-budget, put-budget-action; aws cur describe-report-definitions; aws athena start-query-execution; aws sns create-topic / subscribe; aws events put-rule / put-targets; aws lambda create-function; aws resourcegroupstaggingapi tag-resources; aws...6metadata:7 source: https://skillmd.com/skills/jhkchan/cost-anomaly-response-automator8 domain: aws-cloudops9 complexity: high10 requires_llm: 'true'11 phase: '4'12 supports_pipeline: 'true'13 entry_point: 'false'14 family: FinOps15 task_type: automate16 skill_class: capability17 lifecycle_status: active18 verdict_shape: AUTOMATED | MANUAL_STEP_REQUIRED19 when_to_use: Designing an automated cost-anomaly response for AWS, wiring Cost Anomaly Detection or AWS Budgets to a notification (Slack, Teams, email) or remediation (tag suspect resources, attach an IAM deny policy, stop EC2), building the CUR Athena top-spenders query that feeds the response pipeline, layering Amazon Q cost-optimization recommendations onto anomaly alerts, or hardening an existing spend-response workflow with dry-run, approval gate, and audit.20 when_not_to_use: Manual cost triage — this skill designs automation; use a human-driven cost review for one-off investigations., RI/SP purchasing strategy — commitment decisions are strategic; use a Savings Plan negotiation skill, not a real-time response pipeline., Billing accuracy disputes — use AWS Support; this skill automates response, not charge correction., Showback/chargeback reporting — use CUR + Athena + QuickSight; this skill is for anomaly response, not periodic reporting.21 activation_triggers: automate cost anomaly response, Cost Anomaly Detection to Slack, Budgets action on cost overrun, SNS alert on spend anomaly, EventBridge Lambda cost remediation, stop EC2 on budget breach, IAM deny policy budget action, CUR Athena top spenders, Amazon Q cost optimization, cost budget auto-action, tag resources on anomaly, anomaly subscription SNS22 invocation_schema: "{output: 'Deterministic block: DETECTION_SOURCE / RESPONSE_SCOPE / VERDICT / WORKFLOW\n / GUARDRAILS / AUDIT / FINDINGS / REMEDIATION. VERDICT is AUTOMATED when complete\n with dry-run, scoped IAM, approval gate before resource-stopping actions, and\n CloudTrail-auditable record; MANUAL_STEP_REQUIRED when a guardrail or coverage\n gate fails.', properties: {detection_source: {description: The detection source\n that triggers the workflow., enum: [cad, budgets, ce-anomaly, cur, q-recommendations],\n type: enum}, existing_workflow: {description: 'Existing EventBridge rule + Lambda\n or Step Functions definition. When provided, runs the guardrail + audit gate.',\n type: object}, response_scope: {description: Which response phases to automate.,\n enum: [notify, tag, budget-action, full-playbook, cur-analysis], type: enum},\n severity_threshold: {description: USD impact (CAD) or % of budget (Budgets). Default\n 100 USD / 80%., type: number}}, required: [detection_source, response_scope],\n type: object}"23 version: 0.1.024 author: Jacky Chan — AWS Community Builder25 keywords: Cost Anomaly Detection, CAD, AWS Budgets, cost budget, budget action, anomaly subscription, SNS alert, Cost Explorer, Cost and Usage Report, CUR, Athena top spenders, Amazon Q cost optimization, EventBridge, Lambda remediation, Slack notification, Teams notification, FinOps, cost governance, EC2 stop budget action, IAM policy budget action, spend automation26 tags: finops, cost-anomaly, budgets, automation, cost-explorer, cur, eventbridge, lambda27---2829# Cost Anomaly Response Automator3031## What this skill does3233Designs automated AWS cost-anomaly response workflows that move a34spend spike from detection to actionable notification (or scoped35remediation) without human latency. Supports five detection sources36(Cost Anomaly Detection, AWS Budgets, Cost Explorer anomaly view, CUR37Athena analysis, Amazon Q cost-optimization recommendations), five38response patterns (notify, tag, budget-action, CUR top-spenders39drill-down, full-playbook), and three orchestration surfaces40(EventBridge + Lambda, EventBridge + Step Functions, Budgets native41actions).4243The verdict is binary: **AUTOMATED** when the workflow is complete,44includes dry-run, has scoped IAM, lands an approval gate before any45resource-stopping action, and writes a CloudTrail-auditable record;46**MANUAL_STEP_REQUIRED** when any guardrail or coverage gate fails,47with the specific gap enumerated in FINDINGS.4849## STRICT output contract5051Every invocation MUST emit exactly one design or validation block in52this shape — no prose before, no commentary after:5354```text55DETECTION_SOURCE: <cad | budgets | ce-anomaly | cur | q-recommendations>56RESPONSE_SCOPE: <notify | tag | budget-action | cur-analysis | full-playbook>57VERDICT: AUTOMATED | MANUAL_STEP_REQUIRED58WORKFLOW:59 Detection: <monitor or budget name + ARN>60 EventBridge rule: <name or "n/a (Budgets native)">61 Lambda / Step Functions: <arn or name>62 Budgets action: <action name or "none">63 SNS topic: <arn>64 Notification target: <Slack / Teams / email / PagerDuty>65GUARDRAILS:66 - [PASS|FAIL] Dry-run mode implemented67 - [PASS|FAIL] Approval gate before resource-stopping action68 - [PASS|FAIL] Scoped IAM (least privilege)69 - [PASS|FAIL] Idempotency check on Lambda70 - [PASS|FAIL] Kill-switch (Parameter Store or EventBridge disable)71AUDIT:72 - [PASS|FAIL] CloudTrail covers the account73 - [PASS|FAIL] Notification includes anomaly ID + impact USD74 - [PASS|FAIL] Budgets action execution logged75FINDINGS:76 - [INFO|WARN|HIGH|CRITICAL] <observation>77REMEDIATION:78 1. <specific action with CLI command>79 2. <verification command>80```8182A block missing VERDICT, GUARDRAILS, or REMEDIATION is a contract83violation — re-emit the full block.8485## Quick navigation8687| # | Section | Jump when |88|---|---|---|89| 1 | [STRICT output contract](#strict-output-contract) | Confirm the exact block shape before emitting |90| 2 | [Decision tree](#decision-tree--orchestration-selection) | Picking the right orchestration surface |91| 3 | [Detection sources](#detection-sources) | CAD / Budgets / CE / CUR / Q |92| 4 | [Response patterns](#response-patterns) | Notify / tag / budget-action / CUR |93| 5 | [Step Functions orchestration](#step-functions-orchestration) | Multi-phase full-playbook |94| 6 | [Guardrails](#guardrails-mandatory) | Dry-run, approval gate, kill-switch |95| 7 | [Output format](#output-format--worked-examples) | Full AUTOMATED and MANUAL_STEP_REQUIRED examples |96| 8 | [NEVER anti-patterns](#never-these-things) | Top taboos for spend-response automation |97| 9 | [Expert heuristic](#expert-heuristic--the-60-second-triage) | The 60-second design triage |98| 10 | [Recent AWS features](#recent-aws-features-2024-2026) | What changed in CAD/Budgets/Q in 24 months |99100## Mindset101102**One-line takeaway:** spend-response automation trades blast radius103for speed — a fast wrong action (stopping every EC2 instance in prod)104is more expensive than the anomaly you are trying to contain. The105workflow's job is to surface the spike; the guardrail's job is to106ensure the automation does not amplify the damage.107108Three facts shape every cost-anomaly automation decision:109110- **Notification is reversible; remediation is not.** Posting a Slack111 message is reversible. Attaching an IAM deny policy is reversible.112 Stopping an EC2 instance causes an outage. Terminating is113 irreversible. Default to notify + tag; require a human-approval gate114 before any availability-affecting action.115- **CAD detects anomalies on a 6-24 hour lag, not in real time.** CAD116 evaluates daily or weekly cadences; the spike at 09:00 UTC likely117 started 12-24 hours ago. Budgets are similar. Near-real-time118 detection requires CloudWatch billing alarms (4h poll) or119 CUR/Athena on a schedule.120- **The kill-switch is more important than the trigger.** A workflow121 that fires on every CAD anomaly above USD 100 is fine if scoped.122 Without a kill-switch, a misconfigured monitor, load test, or123 marketing launch can trigger dozens of actions per hour.124125## Pre-flight: spec gate (run before generation)126127| Attribute | Required | Effect on plan |128|---|---|---|129| `detection_source` | YES | Determines the EventBridge source or Budgets native trigger |130| `response_scope` | YES | Determines the actions (notify only, full-playbook, etc.) |131| `severity_threshold` | Recommended | USD impact (CAD) or % of budget (Budgets). Default 100 USD / 80%. |132| `target_regions` | Recommended | Cost is global; Budgets actions are per-region. |133| `approval_required` | RECOMMENDED | Required true if response_scope includes budget-action with stop. |134| `existing_workflow` | For validation | Skip generation; run guardrail + audit gates. |135136**If the spec is incomplete**, emit:137138```text139DETECTION_SOURCE: <unknown>140RESPONSE_SCOPE: <unknown>141VERDICT: MANUAL_STEP_REQUIRED142REASON: Spec is missing required fields (<list>).143REQUIRED:144 - detection_source (cad | budgets | ce-anomaly | cur | q-recommendations)145 - response_scope (notify | tag | budget-action | cur-analysis | full-playbook)146REMEDIATION: Provide both fields. Example: "notify Slack on any CAD147 anomaly above USD 500" maps to detection_source=cad,148 response_scope=notify, severity_threshold=500.149```150151Live-account pre-flight commands (CAD enabled, CUR exists, SNS topic, Lambda role scope, Budgets enabled): [references/diagnostic-commands.md](references/diagnostic-commands.md).152153## Decision tree — orchestration selection154155Apply top-to-bottom. First matching rule wins.156157```158START159 |160 +-- notify only? -------------> EventBridge rule + Lambda161 | (Lambda formats and posts to Slack/Teams/email)162 +-- tag resources? -----------> EventBridge rule + Lambda163 | (Lambda calls resourcegroupstaggingapi:TagResources)164 +-- budget-action? -----------> AWS Budgets native action165 | (IAM policy attach, EC2 stop, SNS notify)166 +-- cur-analysis? ------------> EventBridge schedule + Lambda/Athena167 | (Athena top-spenders, post summary to Slack)168 +-- full-playbook? -----------> EventBridge rule + Step Functions169 | (notify -> tag -> wait for approval -> action)170 +-- q-recommendations? -------> EventBridge schedule + Lambda171 | (poll Q, dedupe, post to Slack)172 +-- (unrecognized) -----------> MANUAL_STEP_REQUIRED with mapping hint173```174175**Orchestration surface selection:**176177- **Lambda-only:** single-action responses <15 min (Lambda max).178 Cheapest and simplest.179- **Step Functions:** multi-phase, parallel, or approval-gated180 responses. Required when a destructive action needs an approval gate.181- **Budgets native actions:** IAM policy attach and EC2 stop triggered182 directly by budget breach. No EventBridge wiring; limited to a183 single threshold and a single action per budget.184- **Athena scheduled query:** CUR top-spenders on a schedule. Athena185 writes to S3; a Lambda posts the summary to Slack.186187## Step 0: Expert knowledge — non-obvious cost behaviors188189Full catalog (CAD daily/weekly lag, TotalImpact semantics, Budgets 8-12h evaluation, calendar-month reset, single-threshold actions, IAM-policy vs EC2-stop targeting, CUR 8-24h latency, Glue partitions, SNS confirmation, webhook storage, EventBridge gaps, Q scoping, COH dedupe, monitor types): [references/advanced-patterns.md](references/advanced-patterns.md).190191## Detection sources192193### AWS Cost Anomaly Detection (CAD)194195Monitor and subscription CLI (list monitors, SERVICE and LINKED_ACCOUNT monitors, SNS-wired anomaly subscription, get-anomalies): [references/cad-budgets-action-catalog.md](references/cad-budgets-action-catalog.md).196197### AWS Budgets198199Budget and action CLI (create-budget, 80% SNS notify, 100% IAM deny AUTOMATIC, 120% EC2 stop MANUAL): [references/cad-budgets-action-catalog.md](references/cad-budgets-action-catalog.md).200201### Cost Explorer anomaly view202203Cost Explorer surfaces anomalies in the console under "Cost Anomaly204Detection". The same data is available via `aws ce get-anomalies`. CE205is the visualization; CAD is the engine. Use `get-anomalies`206programmatically and surface in your own dashboard or Slack via207Lambda.208209### CUR analysis automation210211CUR verify + top-spenders Athena SQL + EventBridge daily schedule CLI: [references/cad-budgets-action-catalog.md](references/cad-budgets-action-catalog.md).212213### Amazon Q cost-optimization recommendations214215Cost Optimization Hub get-recommendations CLI + scheduled Lambda poll/dedupe pattern: [references/cad-budgets-action-catalog.md](references/cad-budgets-action-catalog.md).216217## Response patterns218219### 1. Notify (Slack / Teams / email / PagerDuty)220221```python222import json, urllib.request, os223def lambda_handler(event, context):224 webhook = os.environ['SLACK_WEBHOOK_URL'] # from Parameter Store225 record = json.loads(event['Records'][0]['Sns']['Message'])226 impact = record.get('Impact', {}).get('TotalImpact', 'unknown')227 service = record.get('Impact', {}).get('Services', [{}])[0].get('ServiceName', 'unknown')228 msg = {'text': (229 f":moneybag: *Cost Anomaly*\nImpact: ${impact}\n"230 f"Service: {service}\nAnomaly ID: {record.get('AnomalyId','unknown')}\n"231 f"Account: {record.get('AccountId','unknown')}")}232 urllib.request.urlopen(urllib.request.Request(233 webhook, json.dumps(msg).encode(), {'Content-Type': 'application/json'}))234```235236### 2. Tag suspect resources237238```python239import boto3, json, os240tag_api = boto3.client('resourcegroupstaggingapi')241def lambda_handler(event, context):242 record = json.loads(event['Records'][0]['Sns']['Message'])243 anomaly_id = record['AnomalyId']244 resources = json.loads(os.environ['SUSPECT_RESOURCES']) # populated by Step Functions CUR query245 tag_api.tag_resources(ResourceARNList=resources,246 Tags={'CostAnomaly': anomaly_id, 'Investigate': 'true'})247```248249### 3. Budgets native actions250251Budgets actions run in the Budgets service — no EventBridge or Lambda252for the action itself. Use `APPLY_IAM_POLICY` for soft containment253(deny new resource creation) and `RUN_SSM_DOCUMENTS` with254`STOP_EC2_INSTANCES` for hard containment.255256### 4. CUR top-spenders drill-down257258```python259import boto3260athena = boto3.client('athena')261def lambda_handler(event, context):262 query = '''SELECT lineitem_product_servicename, resource_id,263 SUM(lineitem_unblendedcost) AS spend264 FROM "cur"."cur_table"265 WHERE year='{y}' AND month='{m}'266 GROUP BY 1, 2 HAVING SUM(lineitem_unblendedcost) > 100267 ORDER BY spend DESC LIMIT 20'''.format(y='2026', m='08')268 return {'QueryExecutionId': athena.start_query_execution(269 QueryString=query, QueryExecutionContext={'Database': 'cur'},270 ResultConfiguration={'OutputLocation': 's3://cur-athena-results-us-east-1/'}271 )['QueryExecutionId']}272```273274### 5. Full-playbook (Step Functions)275276Full state-machine JSON (kill-switch check -> notify -> tag -> SQS task-token approval -> optional Budgets action -> close): [references/advanced-patterns.md](references/advanced-patterns.md).277278## Step Functions orchestration279280For full-playbook cost response (multi-phase, approval-gated), use281Step Functions. The state machine above orchestrates the canonical282pattern: kill-switch check -> notify -> tag -> wait for approval ->283optional action -> close.284285| Pattern | Use when | Trade-off |286|---|---|---|287| `Wait` state with fixed duration | One-shot timer ("wait 1h, then auto-stop") | Stays "Running"; clutters dashboard |288| `Task` with `waitForTaskToken` | Human callback via SQS/CLI | Pauses cleanly; resumes on callback |289290Always prefer task-token callback for human approval gates.291292## Guardrails (MANDATORY)293294Every cost-anomaly automation MUST include:2952961. **A kill-switch checked BEFORE any action.** Parameter Store297 (`/cost/kill-switch`), Lambda guard, or EventBridge rule disable.2982. **Dry-run mode for the first deployment.** Set the workflow to299 notify-only for 1-2 weeks; promote to actions after.3003. **An approval gate before any resource-stopping action.** Use Step301 Functions `Task` with `waitForTaskToken` and an SQS queue.3024. **Scoped IAM roles.** `ce:GetAnomalies` (read), `sns:Publish` on303 the topic, `resourcegroupstaggingapi:TagResources` on specific304 ARNs — NOT `*:*` on `*`.3055. **Idempotency.** Handle multiple triggers for the same anomaly.306 Use `AnomalyId` as the dedupe key (DynamoDB or Parameter Store).3076. **No destructive actions without explicit approval.** Notification,308 tagging, IAM deny (reversible) are allowed without approval. EC2309 stop/terminate, resource deletion require an approval gate.310311```bash312# Kill-switch pattern313aws ssm put-parameter --name /cost/kill-switch --value "enabled" --type String314aws ssm put-parameter --name /cost/kill-switch --value "disabled" \315 --type String --overwrite # one-command disable316```317318## Output format — worked examples319320### Worked example — AUTOMATED full-playbook321322```text323DETECTION_SOURCE: cad324RESPONSE_SCOPE: full-playbook325VERDICT: AUTOMATED326WORKFLOW:327 Detection: ec2-spend-monitor (arn:aws:ce::111122223333:anomalymonitor/abc-123)328 Anomaly subscription: prod-cost-anomaly-sub (threshold USD 100, daily)329 SNS topic: arn:aws:sns:us-east-1:111122223333:cost-anomaly-alerts330 Lambda: cost-notify-slack, cost-tag-resources, cost-budget-action331 Step Functions: arn:aws:states:us-east-1:111122223333:stateMachine:cost-full-playbook332 Budgets action: monthly-ec2-budget (IAM deny 100%, EC2 stop 120%)333 Kill-switch: Parameter Store /cost/kill-switch334GUARDRAILS:335 - [PASS] Dry-run 2026-07-15 to 2026-07-29 (14 days, notify-only)336 - [PASS] Approval gate via SQS task token before EC2 stop337 - [PASS] Lambda role scoped to ce:GetAnomalies, sns:Publish,338 resourcegroupstaggingapi:TagResources, budgets:ExecuteBudgetAction339 - [PASS] Idempotency: DynamoDB cost-anomaly-dedupe keyed by AnomalyId340 - [PASS] Kill-switch checked first in state machine341AUDIT:342 - [PASS] CloudTrail org trail covers 111122223333343 - [PASS] Slack notification includes AnomalyId, Impact USD, Service344 - [PASS] Budgets action execution logged; tagged CostAnomaly=<AnomalyId>345FINDINGS:346 - [INFO] SNS subscription confirmed; CAD evaluates daily (6-24h latency)347 - [WARN] CUR/Athena top-spenders query runs on a 12h delay348REMEDIATION: aws cloudformation deploy --stack-name prod-cost-workflow \349 --template-file cost-workflow.yaml --capabilities CAPABILITY_NAMED_IAM350```351352### Worked example — MANUAL_STEP_REQUIRED (missing approval gate)353354Full MANUAL_STEP_REQUIRED example (Budgets EC2 stop AUTOMATIC at 120%, no approval gate): [references/worked-examples.md](references/worked-examples.md).355356## NEVER (these things)357358- **NEVER deploy a budget EC2-stop action without an approval gate.**359 Budgets native `RUN_SSM_DOCUMENTS` with `STOP_EC2_INSTANCES` and360 `ApprovalModel=AUTOMATIC` stops instances the moment the threshold361 crosses — including during a billing-cycle lag when actual spend has362 already returned to normal. The stop causes an outage that costs363 more than the anomaly. Use `ApprovalModel=MANUAL` or wire the stop364 behind a Step Functions task-token approval gate.365366- **NEVER grant the cost-response Lambda `ec2:*` or `iam:*` on `*`.**367 Scope to `ce:GetAnomalies`, `resourcegroupstaggingapi:TagResources`368 on specific ARNs, `budgets:ExecuteBudgetAction` on specific budget369 ARNs. A Lambda that can stop any EC2 instance or attach any IAM370 policy is a privilege-escalation target.371372- **NEVER assume SNS notifications will be delivered.** SNS requires373 endpoint confirmation. An unconfirmed subscription silently drops374 messages. Always send a test message after creating the topic.375376- **NEVER hardcode Slack/Teams webhook URLs in Lambda code.** Store377 in Parameter Store (free, encrypted by default) or Secrets Manager378 (paid, KMS-encrypted, rotation support). A hardcoded URL leaked via379 CloudTrail `GetFunctionConfiguration` lets anyone post to your380 Slack channel.381382- **NEVER skip the dry-run window.** A workflow deployed straight to383 live without a 1-2 week dry-run (notify-only) period will misfire384 on the first real anomaly — wrong Slack channel, malformed385 notification, idempotency miss, or scoped-IAM gap.386387- NEVER terminate EC2 instances from cost automation. Stopping is388 reversible; terminating destroys the resource and its EBS volumes.389 Terminate decisions require human judgment and are out of scope.390391- NEVER rely on Budgets for real-time detection. Budgets evaluates392 every 8-12 hours; CAD evaluates daily/weekly. For sub-hour393 detection, use CloudWatch billing alarms (4h poll) or CUR Athena.394395- NEVER attach an IAM deny-all policy to a role the Lambda or Step396 Functions execution role assumes. The deny-all cascades and blocks397 the workflow itself. Apply deny-all only to user-serving roles.398399- NEVER use `ApprovalModel=AUTOMATIC` for Budgets actions with400 `RUN_SSM_DOCUMENTS`. Use `MANUAL` for EC2/RDS stop. Reserve401 `AUTOMATIC` for `APPLY_IAM_POLICY` (reversible) and402 `SNS_NOTIFICATION`.403404- NEVER forget to dedupe Amazon Q / Cost Optimization Hub405 recommendations by `recommendationId`. A daily Lambda poll without406 dedupe reposts the same recommendation daily, creating Slack noise407 that trains the team to ignore the channel.408409## Expert heuristic — the 60-second triage410411When handed a cost-response design request, run this 60-second triage412before drafting the workflow:4134141. **Identify the detection source.** CAD (anomaly ML), Budgets415 (threshold), CUR/Athena (top-spenders), or Q (recommendations).4162. **Identify the response severity.** Notify-only (reversible, no417 approval needed) vs resource-affecting (approval gate required).4183. **Identify the latency expectation.** CAD = 6-24h. Budgets = 8-12h.419 CUR/Athena = schedule-dependent. Set expectations explicitly.4204. **Identify the kill-switch.** Parameter Store, EventBridge disable,421 or Lambda guard. No kill-switch = MANUAL_STEP_REQUIRED.4225. **Identify the dry-run plan.** Ship with a 1-2 week dry-run423 (notify-only) before going live with actions.424425If any of the five is missing or unclear, emit MANUAL_STEP_REQUIRED.426427## Pre-flight safety checks (run before any deploy)428429- **MANDATORY CONFIRMATION GATE.** Before any state-changing operation430 (`cloudformation deploy`, `events put-rule`, `budgets431 put-budget-action`, `lambda create-function`), emit and await432 operator approval.433- **Dry-run first.** Deploy with `response_scope=notify` for 1-2 weeks434 before promoting to `budget-action` or `full-playbook`.435- **Validate the kill-switch.** Set `/cost/kill-switch` to "disabled"436 and verify a test anomaly does NOT trigger the action.437- **Verify Slack/Teams webhook.** Send a test message before relying438 on it. Capture existing Budgets configuration before deploying new439 actions.440- **Bulk operation safety limit.** Slice multi-account deploys into441 batches of at most 3 accounts; emit per-account CONFIRM per batch.442443## Edge-case handling444445Edge-case catalog (deleted resource, cross-account rollup, planned spike, CUR schema change, stale instance list): [references/advanced-patterns.md](references/advanced-patterns.md).446447## Recent AWS features (2024-2026)448449What changed in 24 months (CAD ML impact, Budgets SSM documents, Cost Optimization Hub, Amazon Q, CUR 2.0 Parquet, calendar-month reset): [references/advanced-patterns.md](references/advanced-patterns.md).450451## References (load on demand)452453- [Worked examples](references/worked-examples.md) - MANUAL_STEP_REQUIRED worked example: Budgets EC2 stop at 120% with no approval gate454- [Diagnostic commands](references/diagnostic-commands.md) - live-account pre-flight commands (CAD monitors, CUR, SNS, Lambda role, Budgets)455- [Advanced patterns](references/advanced-patterns.md) - Step 0 non-obvious cost behaviors, full-playbook Step Functions state machine, edge-case handling, recent AWS features456- [CAD/Budgets/Athena action catalog](references/cad-budgets-action-catalog.md) - detection-source CLI (CAD monitors/subscriptions, Budgets + native actions, CUR top-spenders query, Cost Optimization Hub polling)457458## Domain459460AWS CloudOps / FinOps — cost anomaly response automation.461462## AWS documentation463464- **AWS Cost Anomaly Detection** — https://docs.aws.amazon.com/cost-management/latest/userguide/ce-anomaly-detection.html465- **AWS Budgets** — https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html466- **AWS Budgets actions** — https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-controls.html467- **Cost and Usage Report** — https://docs.aws.amazon.com/cur/latest/userguide/what-is-cur.html468- **Cost Optimization Hub** — https://docs.aws.amazon.com/cost-optimization-hub/latest/userguide/what-is-cost-optimization-hub.html469- **Amazon Q Business** — https://docs.aws.amazon.com/amazonq/latest/qbusiness-ug/what-is.html470- **AWS Cost Explorer** — https://docs.aws.amazon.com/cost-management/latest/userguide/ce-what-is.html471- **Athena CUR queries** — https://docs.aws.amazon.com/cur/latest/userguide/cur-athena.html472- **AWS FinOps Blog** — https://aws.amazon.com/blogs/cost-management/