Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AWS CloudWatch Alarm - Anomaly detection #9828

Merged
merged 4 commits into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions aws/resource_aws_cloudwatch_metric_alarm.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,15 @@ func resourceAwsCloudWatchMetricAlarm() *schema.Resource {
ConflictsWith: []string{"extended_statistic", "metric_query"},
},
"threshold": {
Type: schema.TypeFloat,
Required: true,
Type: schema.TypeFloat,
Optional: true,
ConflictsWith: []string{"threshold_metric_id"},
},
"threshold_metric_id": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"threshold"},
ValidateFunc: validation.StringLenBetween(1, 255),
},
"actions_enabled": {
Type: schema.TypeBool,
Expand Down Expand Up @@ -307,6 +314,7 @@ func resourceAwsCloudWatchMetricAlarmRead(d *schema.ResourceData, meta interface
d.Set("period", a.Period)
d.Set("statistic", a.Statistic)
d.Set("threshold", a.Threshold)
d.Set("threshold_metric_id", a.ThresholdMetricId)
d.Set("unit", a.Unit)
d.Set("extended_statistic", a.ExtendedStatistic)
d.Set("treat_missing_data", a.TreatMissingData)
Expand Down Expand Up @@ -368,7 +376,6 @@ func getAwsCloudWatchPutMetricAlarmInput(d *schema.ResourceData) cloudwatch.PutM
AlarmName: aws.String(d.Get("alarm_name").(string)),
ComparisonOperator: aws.String(d.Get("comparison_operator").(string)),
EvaluationPeriods: aws.Int64(int64(d.Get("evaluation_periods").(int))),
Threshold: aws.Float64(d.Get("threshold").(float64)),
TreatMissingData: aws.String(d.Get("treat_missing_data").(string)),
Tags: tagsFromMapCloudWatch(d.Get("tags").(map[string]interface{})),
}
Expand Down Expand Up @@ -412,6 +419,12 @@ func getAwsCloudWatchPutMetricAlarmInput(d *schema.ResourceData) cloudwatch.PutM
params.EvaluateLowSampleCountPercentile = aws.String(v.(string))
}

if v, ok := d.GetOk("threshold_metric_id"); ok {
params.ThresholdMetricId = aws.String(v.(string))
} else {
params.Threshold = aws.Float64(d.Get("threshold").(float64))
}

var alarmActions []*string
if v := d.Get("alarm_actions"); v != nil {
for _, v := range v.(*schema.Set).List() {
Expand Down
43 changes: 43 additions & 0 deletions aws/resource_aws_cloudwatch_metric_alarm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,13 @@ func TestAccAWSCloudWatchMetricAlarm_expression(t *testing.T) {
resource.TestCheckResourceAttr("aws_cloudwatch_metric_alarm.foobar", "metric_query.#", "2"),
),
},
{
Config: testAccAWSCloudWatchMetricAlarmConfigWithAnomalyDetectionExpression(rInt),
Check: resource.ComposeTestCheckFunc(
testAccCheckCloudWatchMetricAlarmExists("aws_cloudwatch_metric_alarm.foobar", &alarm),
resource.TestCheckResourceAttr("aws_cloudwatch_metric_alarm.foobar", "metric_query.#", "2"),
),
},
{
Config: testAccAWSCloudWatchMetricAlarmConfigWithExpressionWithQueryUpdated(rInt),
Check: resource.ComposeTestCheckFunc(
Expand Down Expand Up @@ -625,6 +632,42 @@ resource "aws_cloudwatch_metric_alarm" "foobar" {
`, rInt)
}

func testAccAWSCloudWatchMetricAlarmConfigWithAnomalyDetectionExpression(rInt int) string {
return fmt.Sprintf(`
resource "aws_cloudwatch_metric_alarm" "foobar" {
alarm_name = "terraform-test-foobar%d"
comparison_operator = "GreaterThanUpperThreshold"
evaluation_periods = "2"
threshold_metric_id = "e1"
alarm_description = "This metric monitors ec2 cpu utilization"
insufficient_data_actions = []

metric_query {
id = "e1"
expression = "ANOMALY_DETECTION_BAND(m1)"
label = "CPUUtilization (Expected)"
return_data = "true"
}

metric_query {
id = "m1"
return_data = "true"
metric {
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "120"
stat = "Average"
unit = "Count"

dimensions = {
InstanceId = "i-abc123"
}
}
}
}
`, rInt)
}

func testAccAWSCloudWatchMetricAlarmConfigWithExpressionUpdated(rInt int) string {
return fmt.Sprintf(`
resource "aws_cloudwatch_metric_alarm" "foobar" {
Expand Down
40 changes: 37 additions & 3 deletions website/docs/r/cloudwatch_metric_alarm.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,40 @@ resource "aws_cloudwatch_metric_alarm" "foobar" {
}
```

```hcl
resource "aws_cloudwatch_metric_alarm" "xx_anomaly_detection" {
alarm_name = "terraform-test-foobar"
comparison_operator = "GreaterThanUpperThreshold"
evaluation_periods = "2"
threshold_metric_id = "e1"
alarm_description = "This metric monitors ec2 cpu utilization"
insufficient_data_actions = []

metric_query {
id = "e1"
expression = "ANOMALY_DETECTION_BAND(m1)"
label = "CPUUtilization (Expected)"
return_data = "true"
}

metric_query {
id = "m1"
return_data = "true"
metric {
metric_name = "CPUUtilization"
namespace = "AWS/EC2"
period = "120"
stat = "Average"
unit = "Count"

dimensions = {
InstanceId = "i-abc123"
}
}
}
}
```

## Example of monitoring Healthy Hosts on NLB using Target Group and NLB

```hcl
Expand All @@ -130,7 +164,6 @@ resource "aws_cloudwatch_metric_alarm" "xxx_nlb_healthyhosts" {
LoadBalancer = aws_lb.lb.arn_suffix
}
}

```

~> **NOTE:** You cannot create a metric alarm consisting of both `statistic` and `extended_statistic` parameters.
Expand All @@ -144,7 +177,7 @@ for details about valid values.
The following arguments are supported:

* `alarm_name` - (Required) The descriptive name for the alarm. This name must be unique within the user's AWS account
* `comparison_operator` - (Required) The arithmetic operation to use when comparing the specified Statistic and Threshold. The specified Statistic value is used as the first operand. Either of the following is supported: `GreaterThanOrEqualToThreshold`, `GreaterThanThreshold`, `LessThanThreshold`, `LessThanOrEqualToThreshold`.
* `comparison_operator` - (Required) The arithmetic operation to use when comparing the specified Statistic and Threshold. The specified Statistic value is used as the first operand. Either of the following is supported: `GreaterThanOrEqualToThreshold`, `GreaterThanThreshold`, `LessThanThreshold`, `LessThanOrEqualToThreshold`. Additionally, the values `LessThanLowerOrGreaterThanUpperThreshold`, `LessThanLowerThreshold`, and `GreaterThanUpperThreshold` are used only for alarms based on anomaly detection models.
* `evaluation_periods` - (Required) The number of periods over which data is compared to the specified threshold.
* `metric_name` - (Optional) The name for the alarm's associated metric.
See docs for [supported metrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html).
Expand All @@ -153,7 +186,8 @@ The following arguments are supported:
* `period` - (Optional) The period in seconds over which the specified `statistic` is applied.
* `statistic` - (Optional) The statistic to apply to the alarm's associated metric.
Either of the following is supported: `SampleCount`, `Average`, `Sum`, `Minimum`, `Maximum`
* `threshold` - (Required) The value against which the specified statistic is compared.
* `threshold` - (Optional) The value against which the specified statistic is compared. This parameter is required for alarms based on static thresholds, but should not be used for alarms based on anomaly detection models.
* `threshold_metric_id` - (Optional) If this is an alarm based on an anomaly detection model, make this value match the ID of the ANOMALY_DETECTION_BAND function.
* `actions_enabled` - (Optional) Indicates whether or not actions should be executed during any changes to the alarm's state. Defaults to `true`.
* `alarm_actions` - (Optional) The list of actions to execute when this alarm transitions into an ALARM state from any other state. Each action is specified as an Amazon Resource Name (ARN).
* `alarm_description` - (Optional) The description for the alarm.
Expand Down