Skip to content

Resource: awsCloudwatchMetricAlarm

Provides a CloudWatch Metric Alarm resource.

Example Usage

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudwatchMetricAlarm.CloudwatchMetricAlarm(this, "foobar", {
  alarmDescription: "This metric monitors ec2 cpu utilization",
  alarmName: "terraform-test-foobar5",
  comparisonOperator: "GreaterThanOrEqualToThreshold",
  evaluationPeriods: 2,
  insufficientDataActions: [],
  metricName: "CPUUtilization",
  namespace: "AWS/EC2",
  period: 120,
  statistic: "Average",
  threshold: 80,
});

Example in Conjunction with Scaling Policies

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsAutoscalingPolicyBat = new aws.autoscalingPolicy.AutoscalingPolicy(
  this,
  "bat",
  {
    adjustmentType: "ChangeInCapacity",
    autoscalingGroupName: "${aws_autoscaling_group.bar.name}",
    cooldown: 300,
    name: "foobar3-terraform-test",
    scalingAdjustment: 4,
  }
);
const awsCloudwatchMetricAlarmBat =
  new aws.cloudwatchMetricAlarm.CloudwatchMetricAlarm(this, "bat_1", {
    alarmActions: [awsAutoscalingPolicyBat.arn],
    alarmDescription: "This metric monitors ec2 cpu utilization",
    alarmName: "terraform-test-foobar5",
    comparisonOperator: "GreaterThanOrEqualToThreshold",
    dimensions: {
      AutoScalingGroupName: "${aws_autoscaling_group.bar.name}",
    },
    evaluationPeriods: 2,
    metricName: "CPUUtilization",
    namespace: "AWS/EC2",
    period: 120,
    statistic: "Average",
    threshold: 80,
  });
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsCloudwatchMetricAlarmBat.overrideLogicalId("bat");

Example with an Expression

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudwatchMetricAlarm.CloudwatchMetricAlarm(this, "foobar", {
  alarmDescription: "Request error rate has exceeded 10%",
  alarmName: "terraform-test-foobar",
  comparisonOperator: "GreaterThanOrEqualToThreshold",
  evaluationPeriods: 2,
  insufficientDataActions: [],
  metricQuery: [
    {
      expression: "m2/m1*100",
      id: "e1",
      label: "Error Rate",
      returnData: "true",
    },
    {
      id: "m1",
      metric: {
        dimensions: [
          {
            loadBalancer: "app/web",
          },
        ],
        metricName: "RequestCount",
        namespace: "AWS/ApplicationELB",
        period: 120,
        stat: "Sum",
        unit: "Count",
      },
    },
    {
      id: "m2",
      metric: {
        dimensions: [
          {
            loadBalancer: "app/web",
          },
        ],
        metricName: "HTTPCode_ELB_5XX_Count",
        namespace: "AWS/ApplicationELB",
        period: 120,
        stat: "Sum",
        unit: "Count",
      },
    },
  ],
  threshold: 10,
});
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudwatchMetricAlarm.CloudwatchMetricAlarm(
  this,
  "xx_anomaly_detection",
  {
    alarmDescription: "This metric monitors ec2 cpu utilization",
    alarmName: "terraform-test-foobar",
    comparisonOperator: "GreaterThanUpperThreshold",
    evaluationPeriods: 2,
    insufficientDataActions: [],
    metricQuery: [
      {
        expression: "ANOMALY_DETECTION_BAND(m1)",
        id: "e1",
        label: "CPUUtilization (Expected)",
        returnData: "true",
      },
      {
        id: "m1",
        metric: {
          dimensions: [
            {
              instanceId: "i-abc123",
            },
          ],
          metricName: "CPUUtilization",
          namespace: "AWS/EC2",
          period: 120,
          stat: "Average",
          unit: "Count",
        },
        returnData: "true",
      },
    ],
    thresholdMetricId: "e1",
  }
);

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

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.cloudwatchMetricAlarm.CloudwatchMetricAlarm(this, "nlb_healthyhosts", {
  actionsEnabled: "true",
  alarmActions: ["${aws_sns_topic.sns.arn}"],
  alarmDescription: "Number of healthy nodes in Target Group",
  alarmName: "alarmname",
  comparisonOperator: "LessThanThreshold",
  dimensions: {
    LoadBalancer: "${aws_lb.lb.arn_suffix}",
    TargetGroup: "${aws_lb_target_group.lb-tg.arn_suffix}",
  },
  evaluationPeriods: 1,
  metricName: "HealthyHostCount",
  namespace: "AWS/NetworkELB",
  okActions: ["${aws_sns_topic.sns.arn}"],
  period: 60,
  statistic: "Average",
  threshold: "${var.logstash_servers_count}",
});

\~> NOTE: You cannot create a metric alarm consisting of both statistic and extendedStatistic parameters. You must choose one or the other

Argument Reference

See related part of AWS Docs for details about valid values.

The following arguments are supported:

  • alarmName - (Required) The descriptive name for the alarm. This name must be unique within the user's AWS account
  • comparisonOperator - (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.
  • evaluationPeriods - (Required) The number of periods over which data is compared to the specified threshold.
  • metricName - (Optional) The name for the alarm's associated metric. See docs for supported metrics.
  • namespace - (Optional) The namespace for the alarm's associated metric. See docs for the list of namespaces. See docs for supported metrics.
  • period - (Optional) The period in seconds over which the specified statistic is applied. Valid values are 10, 30, or any multiple of 60.
  • statistic - (Optional) The statistic to apply to the alarm's associated metric. Either of the following is supported: sampleCount, average, sum, minimum, maximum
  • 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.
  • thresholdMetricId - (Optional) If this is an alarm based on an anomaly detection model, make this value match the ID of the ANOMALY_DETECTION_BAND function.
  • actionsEnabled - (Optional) Indicates whether or not actions should be executed during any changes to the alarm's state. Defaults to true.
  • alarmActions - (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).
  • alarmDescription - (Optional) The description for the alarm.
  • datapointsToAlarm - (Optional) The number of datapoints that must be breaching to trigger the alarm.
  • dimensions - (Optional) The dimensions for the alarm's associated metric. For the list of available dimensions see the AWS documentation here.
  • insufficientDataActions - (Optional) The list of actions to execute when this alarm transitions into an INSUFFICIENT_DATA state from any other state. Each action is specified as an Amazon Resource Name (ARN).
  • okActions - (Optional) The list of actions to execute when this alarm transitions into an OK state from any other state. Each action is specified as an Amazon Resource Name (ARN).
  • unit - (Optional) The unit for the alarm's associated metric.
  • extendedStatistic - (Optional) The percentile statistic for the metric associated with the alarm. Specify a value between p0.0 and p100.
  • treatMissingData - (Optional) Sets how this alarm is to handle missing data points. The following values are supported: missing, ignore, breaching and notBreaching. Defaults to missing.
  • evaluateLowSampleCountPercentiles - (Optional) Used only for alarms based on percentiles. If you specify ignore, the alarm state will not change during periods with too few data points to be statistically significant. If you specify evaluate or omit this parameter, the alarm will always be evaluated and possibly change state no matter how many data points are available. The following values are supported: ignore, and evaluate.
  • metricQuery (Optional) Enables you to create an alarm based on a metric math expression. You may specify at most 20.
  • tags - (Optional) A map of tags to assign to the resource. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.

\~> NOTE: If you specify at least one metricQuery, you may not specify a metricName, namespace, period or statistic. If you do not specify a metricQuery, you must specify each of these (although you may use extendedStatistic instead of statistic).

Nested fields

metricQuery

  • id - (Required) A short name used to tie this object to the results in the response. If you are performing math expressions on this set of data, this name represents that data and can serve as a variable in the mathematical expression. The valid characters are letters, numbers, and underscore. The first character must be a lowercase letter.
  • accountId - (Optional) The ID of the account where the metrics are located, if this is a cross-account alarm.
  • expression - (Optional) The math expression to be performed on the returned data, if this object is performing a math expression. This expression can use the id of the other metrics to refer to those metrics, and can also use the id of other expressions to use the result of those expressions. For more information about metric math expressions, see Metric Math Syntax and Functions in the Amazon CloudWatch User Guide.
  • label - (Optional) A human-readable label for this metric or expression. This is especially useful if this is an expression, so that you know what the value represents.
  • metric - (Optional) The metric to be returned, along with statistics, period, and units. Use this parameter only if this object is retrieving a metric and not performing a math expression on returned data.
  • period - (Optional) Granularity in seconds of returned data points. For metrics with regular resolution, valid values are any multiple of 60. For high-resolution metrics, valid values are 1, 5, 10, 30, or any multiple of 60.
  • returnData - (Optional) Specify exactly one metricQuery to be true to use that metricQuery result as the alarm.

\~> NOTE: You must specify either metric or expression. Not both.

metric

  • dimensions - (Optional) The dimensions for this metric. For the list of available dimensions see the AWS documentation here.
  • metricName - (Required) The name for this metric. See docs for supported metrics.
  • namespace - (Required) The namespace for this metric. See docs for the list of namespaces. See docs for supported metrics.
  • period - (Required) Granularity in seconds of returned data points. For metrics with regular resolution, valid values are any multiple of 60. For high-resolution metrics, valid values are 1, 5, 10, 30, or any multiple of 60.
  • stat - (Required) The statistic to apply to this metric. See docs for supported statistics.
  • unit - (Optional) The unit for this metric.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • arn - The ARN of the CloudWatch Metric Alarm.
  • id - The ID of the health check.
  • tagsAll - A map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.

Import

CloudWatch Metric Alarm can be imported using the alarmName, e.g.,

$ terraform import aws_cloudwatch_metric_alarm.test alarm-12345