SNS Example in AWS CDK [SQS, Lambda] - Complete Guide

avatar

Borislav Hadzhiev

Thu Apr 29 20213 min read

banner

Photo by Jerry Zhang

Table of Contents #

  1. SNS Topic with Lambda subscription in AWS CDK
  2. SNS Topic with SQS subscription in AWS CDK

Create an SNS Topic in AWS CDK #

In this article we are going to:

  • create an SNS topic
  • subscribe a Lambda function to the SNS topic
  • subscribe an SQS queue to the SNS topic

SNS Topic with Lambda subscription in AWS CDK #

Let's start by creating an SNS topic in CDK, by instantiating the Topic class.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
import * as lambda from '@aws-cdk/aws-lambda'; import {NodejsFunction} from '@aws-cdk/aws-lambda-nodejs'; import * as sns from '@aws-cdk/aws-sns'; import * as subs from '@aws-cdk/aws-sns-subscriptions'; import * as cdk from '@aws-cdk/core'; import * as path from 'path'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ create sns topic const topic = new sns.Topic(this, 'sns-topic', { displayName: 'My SNS topic', }); // ๐Ÿ‘‡ create lambda function const myLambda = new NodejsFunction(this, 'my-lambda', { memorySize: 1024, timeout: cdk.Duration.seconds(5), runtime: lambda.Runtime.NODEJS_14_X, handler: 'main', entry: path.join(__dirname, `/../src/my-lambda/index.ts`), }); // ๐Ÿ‘‡ subscribe Lambda to SNS topic topic.addSubscription(new subs.LambdaSubscription(myLambda)); new cdk.CfnOutput(this, 'snsTopicArn', { value: topic.topicArn, description: 'The arn of the SNS topic', }) } }

Let's go over what we did in the code snippet.

  1. we created an sns topic
  2. we created a lambda function, for which we'll set up an sns trigger source
  3. we subscribed the lambda function to the SNS topic
  4. we created an Output with the ARN of the sns topic. We will write the topic ARN to a file, so we can easily test our application via the AWS CLI

Create the lambda function at src/my-lambda/index.ts and add the following code to the file:

src/my-lambda/index.ts
import {APIGatewayProxyResultV2, SNSEvent} from 'aws-lambda'; export async function main(event: SNSEvent): Promise<APIGatewayProxyResultV2> { const records = event.Records.map(record => { const {Message, Subject, Type} = record.Sns; return {subject: Subject, message: Message, type: Type}; }); console.log('records: ๐Ÿ‘‰', JSON.stringify(records, null, 2)); return { body: JSON.stringify({records}), statusCode: 2000, }; }

The lambda function simply gathers the SNS records into an object and prints them to the console.

Let's execute a deployment:

shell
npx cdk deploy \ --outputs-file ./cdk-outputs.json

We have written the SNS topic ARN to a file named cdk-outputs.json in the root directory.

If we take a look at the Triggers section in the Lambda management console, we can see that SNS is configured as a trigger for the function:

sns trigger lambda

The SNS management console also shows the subscription has been set up:

  • the Protocol is set to Lambda
  • the Endpoint is the function's ARN

sns subscription lambda

Let's publish a message to the SNS topic, you can grab your topic arn from the cdk-outputs.json file in the root directory:

shell
aws sns publish \ --subject "My Subject ๐Ÿš€" \ --message "Hello world ๐ŸŠ" \ --topic-arn "YOUR SNS TOPIC ARN"

If we look at the CloudWatch logs for the Lambda function, we can see that our function has been triggered by SNS:

sns triggered lambda

SNS Topic with SQS subscription in AWS CDK #

Let's subscribe an SQS queue to our SNS topic as well. In order to create the queue we will instantiate the Queue class.

The code for this article is available on GitHub
lib/cdk-starter-stack.ts
import * as sqs from '@aws-cdk/aws-sqs'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props) // ... rest // ๐Ÿ‘‡ create queue const queue = new sqs.Queue(this, 'sqs-queue'); // ๐Ÿ‘‡ subscribe queue to topic topic.addSubscription(new subs.SqsSubscription(queue)); } }

In the code snippet, we created an SQS queue and subscribed the queue to our SNS topic.

Let's deploy the changes:

shell
npx cdk deploy \ --outputs-file ./cdk-outputs.json

The SNS management console, shows that the SQS subscription has also been set up:

sns subscription sqs

The sqs queue currently has 0 messages available:

sqs queue empty

Let's publish another message to the SNS topic to test the sqs integration:

shell
aws sns publish \ --subject "My Subject ๐Ÿš€" \ --message "Hello world ๐ŸŠ" \ --topic-arn "YOUR SNS TOPIC ARN"

After I've published a message to the sns topic, the queue has 1 message available:

sqs queue one message

Clean up #

To delete the resources we've provisioned, execute the destroy command:

shell
npx cdk destroy

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee