How to subscribe an SQS queue to an SNS topic with aws cdk?

Viewed 2109

I first create a queue:

const notificationQueue: sqs.IQueue = new sqs.Queue(this, `${domain}-notificationsQueue`, {
  queueName: `${domain}-notificationsQueue.fifo`,
  fifo: true,
  contentBasedDeduplication: false
});

Now I need to subscribe this queue to an SNS topic (something like this but I need to pass in an IGrantable object - which I don't know how to do)

queue.grantConsumeMessages(grantee: iam.IGrantable)

So how do I create an IGrantable object that references a specific SNS topic?

1 Answers

We can use @aws-cdk/aws-sns-subscriptions

we can import these:

import * as subscriptions from "@aws-cdk/aws-sns-subscriptions";
import * as sns from "@aws-cdk/aws-sns";
import * as sqs from "@aws-cdk/aws-sqs";

use addSubscription method on Sns.

const myTopic = new sns.Topic(this, "MyTopic");
const myQueue = new sqs.Queue(this, "MyQueue");
myTopic.addSubscription(new subscriptions.SqsSubscription(myQueue));
Related