1. Answers
  2. Filtering AWS SNS to SQS messages

How do I filter SQS message body with SNS?

In this guide, we will demonstrate how to filter messages sent from an Amazon SNS topic to an SQS queue using Pulumi. We will define an SNS topic, an SQS queue, and an SNS subscription with a filter policy to ensure only messages matching specific criteria are delivered to the SQS queue.

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create an SNS topic
const snsTopic = new aws.sns.Topic("exampleTopic");

// Create an SQS queue
const sqsQueue = new aws.sqs.Queue("exampleQueue");

// Define the filter policy
const filterPolicy = {
    "attributeName": [{ "numeric": [">", 100] }]
};

// Create an SNS subscription to the SQS queue with a filter policy
const snsSubscription = new aws.sns.TopicSubscription("exampleSubscription", {
    topic: snsTopic.arn,
    protocol: "sqs",
    endpoint: sqsQueue.arn,
    filterPolicy: JSON.stringify(filterPolicy),
});

// Grant the SNS topic permission to send messages to the SQS queue
const queuePolicy = new aws.sqs.QueuePolicy("exampleQueuePolicy", {
    queueUrl: sqsQueue.id,
    policy: sqsQueue.arn.apply(arn => JSON.stringify({
        Version: "2012-10-17",
        Statement: [{
            Effect: "Allow",
            Principal: { Service: "sns.amazonaws.com" },
            Action: "sqs:SendMessage",
            Resource: arn,
            Condition: {
                ArnEquals: { "aws:SourceArn": snsTopic.arn }
            }
        }]
    })),
});

Key Points

  • SNS Topic: Created to publish messages.
  • SQS Queue: Created to receive messages.
  • Filter Policy: Applied to the SNS subscription to filter messages.
  • SNS Subscription: Subscribes the SQS queue to the SNS topic with the filter policy.
  • Queue Policy: Grants the SNS topic permission to send messages to the SQS queue.

Summary

We have successfully set up an SNS topic, an SQS queue, and an SNS subscription with a filter policy using Pulumi. This configuration ensures that only messages matching the filter criteria are delivered to the SQS queue.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up