- Published on
Deploying AWS Cost Anomaly Detection using CDK
- Authors
- Name
- Bobbie Couhbor
AWS Cost Anomaly Detection
AWS Cost Anomaly Detection uses Machine Learning to identify anomalous spending and notify you so you can take action before costs get out of control. A short set up video I recorded is below.
But what if you're looking to automate the deployment and configuration? CDK can be used to get the job done, specifically the cfnAnomalyDetector construct.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { aws_ce as ce } from 'aws-cdk-lib';
export class HelloCdkStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const emailAddress = new cdk.CfnParameter(this, "emailAddress", {
type: "String",
default: "hello@gmail.com",
description: "The email address to notify"});
const thresholdExpression = new cdk.CfnParameter(this, "thresholdExpression", {
type: "String",
default: '{\
"Dimensions": {\
"Key": "ANOMALY_TOTAL_IMPACT_PERCENTAGE",\
"MatchOptions": [ "GREATER_THAN_OR_EQUAL" ],\
"Values": [ "100" ]\
}\
}',
description: "The threshold expression as dictated here https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_AnomalySubscription.html"});
// Create the anomaly monitor
const cfnAnomalyMonitor = new ce.CfnAnomalyMonitor(this, 'MyCfnAnomalyMonitor', {
monitorName: 'MasterAccount',
monitorType: 'DIMENSIONAL',
monitorDimension: 'SERVICE'
});
//Create the alert subscription
const cfnAnomalySubscription = new ce.CfnAnomalySubscription(this, 'MyCfnAnomalySubscription', {
frequency: 'DAILY',
monitorArnList: [cfnAnomalyMonitor.attrMonitorArn],
subscribers: [{
address: emailAddress.valueAsString,
type: 'EMAIL',
status: 'CONFIRMED',
}],
subscriptionName: 'AdminAlert',
thresholdExpression: thresholdExpression.valueAsString
});
}
}
Alternatively, if CloudFormation is your jam:
Parameters:
emailAddress:
Type: String
Default: hello@gmail.com
Description: The email address to notify
thresholdExpression:
Type: String
Default: '{ "Dimensions": { "Key": "ANOMALY_TOTAL_IMPACT_PERCENTAGE", "MatchOptions": [ "GREATER_THAN_OR_EQUAL" ], "Values": [ "100" ] } }'
Description: The threshold expression as dictated here https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_AnomalySubscription.html
Resources:
MyCfnAnomalyMonitor:
Type: AWS::CE::AnomalyMonitor
Properties:
MonitorDimension: SERVICE
MonitorName: MasterAccount
MonitorType: DIMENSIONAL
MyCfnAnomalySubscription:
Type: AWS::CE::AnomalySubscription
Properties:
Frequency: DAILY
MonitorArnList:
- Fn::GetAtt:
- MyCfnAnomalyMonitor
- MonitorArn
Subscribers:
- Address:
Ref: emailAddress
Status: CONFIRMED
Type: EMAIL
SubscriptionName: AdminAlert
ThresholdExpression:
Ref: thresholdExpression