How to create an alarm when AWS DMS replication tasks encounter errors with AWS CDK

To Nha Notes | Oct. 2, 2023, 9:24 p.m.

import * as logs from 'aws-cdk-lib/aws-logs';
import { Unit } from 'aws-cdk-lib/aws-cloudwatch';

declare const alarmTopic: sns.ITopic;

const taskLogGroup = logs.LogGroup.fromLogGroupArn(this, 'TaskLogGroup', `arn:aws:logs:${this.region}:${this.account}:log-group:dms-tasks-${dmsProps.replicationInstanceIdentifier}:*`);

      new logs.MetricFilter(this, 'TaskErrorCount', {

        logGroup: taskLogGroup,

        metricNamespace: 'DMS',

        metricName: 'TaskErrorCount',

        filterPattern: logs.FilterPattern.anyTerm(']E:', 'ERROR', 'Error', 'error'),

        unit: Unit.COUNT

      });

const taskErrorMetric = new cloudwatch.Metric({

            namespace: 'DMS',

            metricName: 'TaskErrorCount',

            label: 'TaskErrorCount',

            period: cdk.Duration.minutes(1),

            statistic: 'Sum',

            unit: cloudwatch.Unit.COUNT,

        });

const taskErrorAlarm = taskErrorMetric.createAlarm(this, `ReplicationTaskErrorAlarm`, {

            alarmName: `${replicationInstanceIdentifier}-task-error`,

            alarmDescription: `Errors have occurred in the replication tasks within the last minute.`,

            threshold: threshold,

            comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,

            evaluationPeriods: 1,

            datapointsToAlarm: 1,

            actionsEnabled: true,

            treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING

        });

        taskErrorAlarm.addAlarmAction(new cloudwatch_actions.SnsAction(alarmTopic));