AnomalyDetectionAlarm L2 construct
CloudWatch Alarm that uses anomaly detection to trigger alarms.
This alarm type is specifically designed for use with anomaly detection operators like LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD.
Example
// Create a metric
const metric = new cloudwatch.Metric({
namespace: 'AWS/EC2',
metricName: 'CPUUtilization',
statistic: 'Average',
period: Duration.hours(1), // Alarm will use the metric's period
});
// Create an anomaly detection alarm
const alarm = new cloudwatch.AnomalyDetectionAlarm(this, 'AnomalyAlarm', {
metric: metric,
evaluationPeriods: 1,
// Number of standard deviations for the band (default: 2)
stdDevs: 2,
// Alarm outside on either side of the band, or just below or above it (default: outside)
comparisonOperator: cloudwatch.ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
alarmDescription: 'Alarm when metric is outside the expected band',
});
# Create a metric
metric = cloudwatch.Metric(
namespace="AWS/EC2",
metric_name="CPUUtilization",
statistic="Average",
period=Duration.hours(1)
)
# Create an anomaly detection alarm
alarm = cloudwatch.AnomalyDetectionAlarm(self, "AnomalyAlarm",
metric=metric,
evaluation_periods=1,
# Number of standard deviations for the band (default: 2)
std_devs=2,
# Alarm outside on either side of the band, or just below or above it (default: outside)
comparison_operator=cloudwatch.ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
alarm_description="Alarm when metric is outside the expected band"
)
// Create a metric
Metric metric = Metric.Builder.create()
.namespace("AWS/EC2")
.metricName("CPUUtilization")
.statistic("Average")
.period(Duration.hours(1))
.build();
// Create an anomaly detection alarm
AnomalyDetectionAlarm alarm = AnomalyDetectionAlarm.Builder.create(this, "AnomalyAlarm")
.metric(metric)
.evaluationPeriods(1)
// Number of standard deviations for the band (default: 2)
.stdDevs(2)
// Alarm outside on either side of the band, or just below or above it (default: outside)
.comparisonOperator(ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD)
.alarmDescription("Alarm when metric is outside the expected band")
.build();
// Install: dotnet add package Amazon.CDK.Lib
// Create a metric
var metric = new Metric(new MetricProps {
Namespace = "AWS/EC2",
MetricName = "CPUUtilization",
Statistic = "Average",
Period = Duration.Hours(1)
});
// Create an anomaly detection alarm
var alarm = new AnomalyDetectionAlarm(this, "AnomalyAlarm", new AnomalyDetectionAlarmProps {
Metric = metric,
EvaluationPeriods = 1,
// Number of standard deviations for the band (default: 2)
StdDevs = 2,
// Alarm outside on either side of the band, or just below or above it (default: outside)
ComparisonOperator = ComparisonOperator.LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
AlarmDescription = "Alarm when metric is outside the expected band"
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Create a metric
metric := cloudwatch.NewMetric(&MetricProps{
Namespace: jsii.String("AWS/EC2"),
MetricName: jsii.String("CPUUtilization"),
Statistic: jsii.String("Average"),
Period: awscdk.Duration_Hours(jsii.Number(1)),
})
// Create an anomaly detection alarm
alarm := cloudwatch.NewAnomalyDetectionAlarm(this, jsii.String("AnomalyAlarm"), &AnomalyDetectionAlarmProps{
Metric: metric,
EvaluationPeriods: jsii.Number(1),
// Number of standard deviations for the band (default: 2)
StdDevs: jsii.Number(2),
// Alarm outside on either side of the band, or just below or above it (default: outside)
ComparisonOperator: cloudwatch.ComparisonOperator_LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD,
AlarmDescription: jsii.String("Alarm when metric is outside the expected band"),
})
Initializer
new AnomalyDetectionAlarm(scope: Construct, id: string, props: AnomalyDetectionAlarmProps)
AnomalyDetectionAlarm(scope: Construct, id: str, props: AnomalyDetectionAlarmProps)
new AnomalyDetectionAlarm(Construct scope, String id, AnomalyDetectionAlarmProps props)
new AnomalyDetectionAlarm(Construct scope, string id, AnomalyDetectionAlarmProps props)
NewAnomalyDetectionAlarm(Scope Construct, Id *string, Props AnomalyDetectionAlarmProps)
Construct Props
actionsEnabledoptionalbooleanactions_enabledoptionalboolactionsEnabledoptionalBooleanActionsEnabledoptionalboolActionsEnabledoptional*bool= true#alarmDescriptionoptionalstringalarm_descriptionoptionalstralarmDescriptionoptionalStringAlarmDescriptionoptionalstringAlarmDescriptionoptional*string#Default: No description
alarmNameoptionalstringalarm_nameoptionalstralarmNameoptionalStringAlarmNameoptionalstringAlarmNameoptional*string#Default: Automatically generated name
comparisonOperatoroptionalComparisonOperatorcomparison_operatoroptionalComparisonOperatorcomparisonOperatoroptionalComparisonOperatorComparisonOperatoroptionalComparisonOperatorComparisonOperatoroptionalComparisonOperator#Default: LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD
Must be one of the anomaly detection operators:
- LESS_THAN_LOWER_OR_GREATER_THAN_UPPER_THRESHOLD
- GREATER_THAN_UPPER_THRESHOLD
- LESS_THAN_LOWER_THRESHOLD
datapointsToAlarmoptionalnumberdatapoints_to_alarmoptionalint | floatdatapointsToAlarmoptionalNumberDatapointsToAlarmoptionaldoubleDatapointsToAlarmoptional*float64= ``evaluationPeriods``#This is used only if you are setting an "M out of N" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon CloudWatch User Guide.
evaluateLowSampleCountPercentileoptionalstringevaluate_low_sample_count_percentileoptionalstrevaluateLowSampleCountPercentileoptionalStringEvaluateLowSampleCountPercentileoptionalstringEvaluateLowSampleCountPercentileoptional*string#Default: Not configured.
Used only for alarms that are based on percentiles.
evaluationPeriodsnumberevaluation_periodsint | floatevaluationPeriodsNumberEvaluationPeriodsdoubleEvaluationPeriods*float64required#Metric objects can be obtained from most resources, or you can construct custom Metric objects by instantiating one.
periodoptionalDurationperiodoptionalDurationperiodoptionalDurationPeriodoptionalDurationPeriodoptionalDurationdeprecated#Default: The period from the metric
Cannot be used with MathExpression objects.
statisticoptionalstringstatisticoptionalstrstatisticoptionalStringStatisticoptionalstringStatisticoptional*stringdeprecated#Default: The statistic from the metric
Can be one of the following:
- "Minimum" | "min"
- "Maximum" | "max"
- "Average" | "avg"
- "Sum" | "sum"
- "SampleCount | "n"
- "pNN.NN"
Cannot be used with MathExpression objects.
stdDevsoptionalnumberstd_devsoptionalint | floatstdDevsoptionalNumberStdDevsoptionaldoubleStdDevsoptional*float64= 2#notes
The higher the value, the wider the band.
- Must be greater than 0. A value of 0 or negative values would not make sense in the context of calculating standard deviations.
- There is no strict maximum value defined, as standard deviations can theoretically extend infinitely. However, in practice, values beyond 5 or 6 standard deviations are rarely used, as they would result in an extremely wide anomaly detection band, potentially missing significant anomalies.
treatMissingDataoptionalTreatMissingDatatreat_missing_dataoptionalTreatMissingDatatreatMissingDataoptionalTreatMissingDataTreatMissingDataoptionalTreatMissingDataTreatMissingDataoptionalTreatMissingData= TreatMissingData.Missing#Properties
alarmRefAlarmReferencealarm_refAlarmReferencealarmRefAlarmReferenceAlarmRefAlarmReferenceAlarmRefAlarmReference#ANOMALY_DETECTION_NO_THRESHOLDnumberanomaly_detection_no_thresholdint | floatANOMALY_DETECTION_NO_THRESHOLDNumberANOMALY_DETECTION_NO_THRESHOLDdoubleANOMALY_DETECTION_NO_THRESHOLD*float64static#notes
Anomaly detection alarms don't have numbered threshold. Instead, they have a dynamically calculated threshold based on the metric math expression that contains a metric expression.
The threshold property is required, but the value is ignored. This constant has the value 0, and has a symbolic name to indicate why the threshold is 0. You can use new AnomalyDetectionAlarm() to avoid having to pass the threshold property at all.
envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironment#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringstatic#Methods
addAlarmAction(...actions: IAlarmAction[]): voiddef add_alarm_action(self, actions: IAlarmAction) -> Nonepublic void addAlarmAction(IAlarmAction actions)public void AddAlarmAction(IAlarmAction actions)func AddAlarmAction(Actions IAlarmAction)#Typically SnsAction or AutoScalingAction.
addAlarmMuteRule(id: string, options: AlarmMuteRuleOptions): AlarmMuteRuledef add_alarm_mute_rule(self, id: str, options: AlarmMuteRuleOptions) -> AlarmMuteRulepublic AlarmMuteRule addAlarmMuteRule(String id, AlarmMuteRuleOptions options)public AlarmMuteRule AddAlarmMuteRule(string id, AlarmMuteRuleOptions options)func AddAlarmMuteRule(Id *string, Options AlarmMuteRuleOptions) AlarmMuteRule#addInsufficientDataAction(...actions: IAlarmAction[]): voiddef add_insufficient_data_action(self, actions: IAlarmAction) -> Nonepublic void addInsufficientDataAction(IAlarmAction actions)public void AddInsufficientDataAction(IAlarmAction actions)func AddInsufficientDataAction(Actions IAlarmAction)#Typically SnsAction or AutoScalingAction.
addOkAction(...actions: IAlarmAction[]): voiddef add_ok_action(self, actions: IAlarmAction) -> Nonepublic void addOkAction(IAlarmAction actions)public void AddOkAction(IAlarmAction actions)func AddOkAction(Actions IAlarmAction)#Typically SnsAction or AutoScalingAction.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.
The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).
fromAlarmArn(scope: Construct, id: string, alarmArn: string): IAlarm@staticmethod def from_alarm_arn(scope: Construct, id: str, alarm_arn: str) -> IAlarmpublic static IAlarm fromAlarmArn(Construct scope, String id, String alarmArn)public static IAlarm FromAlarmArn(Construct scope, string id, string alarmArn)func FromAlarmArn(Scope Construct, Id *string, AlarmArn *string) IAlarmstatic#3 parameters
Parameters
scopescopescopescopeScope— The parent creating construct (usuallythis).ididididId— The construct's name.alarmArnalarm_arnalarmArnalarmArnAlarmArn— Alarm ARN (i.e. arn:aws:cloudwatch:<region>:<account-id>:alarm:Foo).
fromAlarmName(scope: Construct, id: string, alarmName: string): IAlarm@staticmethod def from_alarm_name(scope: Construct, id: str, alarm_name: str) -> IAlarmpublic static IAlarm fromAlarmName(Construct scope, String id, String alarmName)public static IAlarm FromAlarmName(Construct scope, string id, string alarmName)func FromAlarmName(Scope Construct, Id *string, AlarmName *string) IAlarmstatic#3 parameters
Parameters
scopescopescopescopeScope— The parent creating construct (usuallythis).ididididId— The construct's name.alarmNamealarm_namealarmNamealarmNameAlarmName— Alarm Name.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.
Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.
Parameters
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#renderAlarmRule(): stringdef render_alarm_rule(self, ) -> strpublic String renderAlarmRule()public string RenderAlarmRule()func RenderAlarmRule() *string#toAnnotation(): HorizontalAnnotationdef to_annotation(self, ) -> HorizontalAnnotationpublic HorizontalAnnotation toAnnotation()public HorizontalAnnotation ToAnnotation()func ToAnnotation() HorizontalAnnotation#notes
This is useful if you want to represent an Alarm in a non-AlarmWidget. An AlarmWidget can directly show an alarm, but it can only show a single alarm and no other metrics. Instead, you can convert the alarm to a HorizontalAnnotation and add it as an annotation to another graph.
This might be useful if:
You want to show multiple alarms inside a single graph, for example if you have both a "small margin/long period" alarm as well as a "large margin/short period" alarm.
You want to show an Alarm line in a graph with multiple metrics in it.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.