Skip to content

Instantly share code, notes, and snippets.

@archieedwards
Created March 20, 2023 12:09
Show Gist options
  • Save archieedwards/51d35cd7f3e5c1e6d6f2a1107fe4fc6f to your computer and use it in GitHub Desktop.
Save archieedwards/51d35cd7f3e5c1e6d6f2a1107fe4fc6f to your computer and use it in GitHub Desktop.
AWS CDK - queue, lambda & slack alert
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as sqs from "aws-cdk-lib/aws-sqs";
import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
import { Runtime } from "aws-cdk-lib/aws-lambda";
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as cloudwatchActions from "aws-cdk-lib/aws-cloudwatch-actions";
import * as sns from "aws-cdk-lib/aws-sns";
import {
LoggingLevel,
SlackChannelConfiguration,
} from "aws-cdk-lib/aws-chatbot";
import { PrismaFunction } from "../constructs/prisma-function";
export class ExmapleStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const deadLetterQueue = new sqs.Queue(this, "DeadLetterQueue");
const queue = new sqs.Queue(this, "Queue", {
visibilityTimeout: cdk.Duration.seconds(300),
deadLetterQueue: {
queue: deadLetterQueue,
maxReceiveCount: 3,
},
});
const consumerFunc = new PrismaFunction(
this,
"AutomationServiceQueueConsumer",
{
entry: "./src/functions/automation-task.ts",
handler: "handler",
runtime: Runtime.NODEJS_18_X,
environment: {
AWS_SQS_URL: queue.queueUrl,
},
logRetention: 7,
databaseUrl: process.env.DATABASE_URL ?? "",
}
);
queue.grantConsumeMessages(consumerFunc);
consumerFunc.addEventSource(new SqsEventSource(queue));
const deadLetterQueueAlarm = new cloudwatch.Alarm(
this,
"DeadLetterQueueAlarm",
{
alarmName: "eveloo-automation-service-dead-letter-queue-alarm",
metric: deadLetterQueue.metricApproximateNumberOfMessagesVisible(),
threshold: 1,
evaluationPeriods: 1,
}
);
const deadLetterQueueTopic = new sns.Topic(this, "DeadLetterQueueTopic", {
topicName: "eveloo-automation-service-dead-letter-queue-alarm-topic",
});
deadLetterQueueAlarm.addAlarmAction(
new cloudwatchActions.SnsAction(deadLetterQueueTopic)
);
new SlackChannelConfiguration(this, "DeadLetterQueueSlackNotification", {
slackChannelId: <channel-id>,
slackWorkspaceId: <workspace-id>,
notificationTopics: [deadLetterQueueTopic],
loggingLevel: LoggingLevel.ERROR,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment