Namespace Amazon.CDK.AWS.SNS
Amazon Simple Notification Service Construct Library
Add an SNS Topic to your stack:
var topic = new Topic(this, "Topic", new TopicProps {
DisplayName = "Customer subscription topic"
});
Add a FIFO SNS topic with content-based de-duplication to your stack:
var topic = new Topic(this, "Topic", new TopicProps {
ContentBasedDeduplication = true,
DisplayName = "Customer subscription topic",
Fifo = true
});
Add an SNS Topic to your stack with a specified signature version, which corresponds to the hashing algorithm used while creating the signature of the notifications, subscription confirmations, or unsubscribe confirmation messages sent by Amazon SNS.
The default signature version is 1
(SHA1
).
SNS also supports signature version 2
(SHA256
).
var topic = new Topic(this, "Topic", new TopicProps {
SignatureVersion = "2"
});
Note that FIFO topics require a topic name to be provided. The required .fifo
suffix will be automatically generated and added to the topic name if it is not explicitly provided.
Subscriptions
Various subscriptions can be added to the topic by calling the
.addSubscription(...)
method on the topic. It accepts a subscription object,
default implementations of which can be found in the
aws-cdk-lib/aws-sns-subscriptions
package:
Add an HTTPS Subscription to your topic:
var myTopic = new Topic(this, "MyTopic");
myTopic.AddSubscription(new UrlSubscription("https://foobar.com/"));
Subscribe a queue to the topic:
Queue queue;
var myTopic = new Topic(this, "MyTopic");
myTopic.AddSubscription(new SqsSubscription(queue));
Note that subscriptions of queues in different accounts need to be manually confirmed by reading the initial message from the queue and visiting the link found in it.
Filter policy
A filter policy can be specified when subscribing an endpoint to a topic.
Example with a Lambda subscription:
using Amazon.CDK.AWS.Lambda;
Function fn;
var myTopic = new Topic(this, "MyTopic");
// Lambda should receive only message matching the following conditions on attributes:
// color: 'red' or 'orange' or begins with 'bl'
// size: anything but 'small' or 'medium'
// price: between 100 and 200 or greater than 300
// store: attribute must be present
myTopic.AddSubscription(new LambdaSubscription(fn, new LambdaSubscriptionProps {
FilterPolicy = new Dictionary<string, SubscriptionFilter> {
{ "color", SubscriptionFilter.StringFilter(new StringConditions {
Allowlist = new [] { "red", "orange" },
MatchPrefixes = new [] { "bl" },
MatchSuffixes = new [] { "ue" }
}) },
{ "size", SubscriptionFilter.StringFilter(new StringConditions {
Denylist = new [] { "small", "medium" }
}) },
{ "price", SubscriptionFilter.NumericFilter(new NumericConditions {
Between = new BetweenCondition { Start = 100, Stop = 200 },
GreaterThan = 300
}) },
{ "store", SubscriptionFilter.ExistsFilter() }
}
}));
Payload-based filtering
To filter messages based on the payload or body of the message, use the filterPolicyWithMessageBody
property. This type of filter policy supports creating filters on nested objects.
Example with a Lambda subscription:
using Amazon.CDK.AWS.Lambda;
Function fn;
var myTopic = new Topic(this, "MyTopic");
// Lambda should receive only message matching the following conditions on message body:
// color: 'red' or 'orange'
myTopic.AddSubscription(new LambdaSubscription(fn, new LambdaSubscriptionProps {
FilterPolicyWithMessageBody = new Dictionary<string, FilterOrPolicy> {
{ "background", FilterOrPolicy.Policy(new Dictionary<string, FilterOrPolicy> {
{ "color", FilterOrPolicy.Filter(SubscriptionFilter.StringFilter(new StringConditions {
Allowlist = new [] { "red", "orange" }
})) }
}) }
}
}));
Example of Firehose Subscription
using Amazon.CDK.AWS.KinesisFirehose.Alpha;
DeliveryStream stream;
var topic = new Topic(this, "Topic");
new Subscription(this, "Subscription", new SubscriptionProps {
Topic = topic,
Endpoint = stream.DeliveryStreamArn,
Protocol = SubscriptionProtocol.FIREHOSE,
SubscriptionRoleArn = "SAMPLE_ARN"
});
DLQ setup for SNS Subscription
CDK can attach provided Queue as DLQ for your SNS subscription. See the SNS DLQ configuration docs for more information about this feature.
Example of usage with user provided DLQ.
var topic = new Topic(this, "Topic");
var dlQueue = new Queue(this, "DeadLetterQueue", new QueueProps {
QueueName = "MySubscription_DLQ",
RetentionPeriod = Duration.Days(14)
});
new Subscription(this, "Subscription", new SubscriptionProps {
Endpoint = "endpoint",
Protocol = SubscriptionProtocol.LAMBDA,
Topic = topic,
DeadLetterQueue = dlQueue
});
CloudWatch Event Rule Target
SNS topics can be used as targets for CloudWatch event rules.
Use the aws-cdk-lib/aws-events-targets.SnsTopic
:
using Amazon.CDK.AWS.CodeCommit;
using Amazon.CDK.AWS.Events.Targets;
Repository repo;
var myTopic = new Topic(this, "Topic");
repo.OnCommit("OnCommit", new OnCommitOptions {
Target = new SnsTopic(myTopic)
});
This will result in adding a target to the event rule and will also modify the topic resource policy to allow CloudWatch events to publish to the topic.
Topic Policy
A topic policy is automatically created when addToResourcePolicy
is called, if
one doesn't already exist. Using addToResourcePolicy
is the simplest way to
add policies, but a TopicPolicy
can also be created manually.
var topic = new Topic(this, "Topic");
var topicPolicy = new TopicPolicy(this, "TopicPolicy", new TopicPolicyProps {
Topics = new [] { topic }
});
topicPolicy.Document.AddStatements(new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "sns:Subscribe" },
Principals = new [] { new AnyPrincipal() },
Resources = new [] { topic.TopicArn }
}));
A policy document can also be passed on TopicPolicy
construction
var topic = new Topic(this, "Topic");
var policyDocument = new PolicyDocument(new PolicyDocumentProps {
AssignSids = true,
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "sns:Subscribe" },
Principals = new [] { new AnyPrincipal() },
Resources = new [] { topic.TopicArn }
}) }
});
var topicPolicy = new TopicPolicy(this, "Policy", new TopicPolicyProps {
Topics = new [] { topic },
PolicyDocument = policyDocument
});
Enforce encryption of data in transit when publishing to a topic
You can enforce SSL when creating a topic policy by setting the enforceSSL
flag:
var topic = new Topic(this, "Topic");
var policyDocument = new PolicyDocument(new PolicyDocumentProps {
AssignSids = true,
Statements = new [] {
new PolicyStatement(new PolicyStatementProps {
Actions = new [] { "sns:Publish" },
Principals = new [] { new ServicePrincipal("s3.amazonaws.com") },
Resources = new [] { topic.TopicArn }
}) }
});
var topicPolicy = new TopicPolicy(this, "Policy", new TopicPolicyProps {
Topics = new [] { topic },
PolicyDocument = policyDocument,
EnforceSSL = true
});
Similiarly you can enforce SSL by setting the enforceSSL
flag on the topic:
var topic = new Topic(this, "TopicAddPolicy", new TopicProps {
EnforceSSL = true
});
topic.AddToResourcePolicy(new PolicyStatement(new PolicyStatementProps {
Principals = new [] { new ServicePrincipal("s3.amazonaws.com") },
Actions = new [] { "sns:Publish" },
Resources = new [] { topic.TopicArn }
}));
Delivery status logging
Amazon SNS provides support to log the delivery status of notification messages sent to topics with the following Amazon SNS endpoints:
Example with a delivery status logging configuration for SQS:
Role role;
var topic = new Topic(this, "MyTopic", new TopicProps {
LoggingConfigs = new [] { new LoggingConfig {
Protocol = LoggingProtocol.SQS,
FailureFeedbackRole = role,
SuccessFeedbackRole = role,
SuccessFeedbackSampleRate = 50
} }
});
A delivery status logging configuration can also be added to your topic by addLoggingConfig
method:
Role role;
var topic = new Topic(this, "MyTopic");
topic.AddLoggingConfig(new LoggingConfig {
Protocol = LoggingProtocol.SQS,
FailureFeedbackRole = role,
SuccessFeedbackRole = role,
SuccessFeedbackSampleRate = 50
});
Note that valid values for successFeedbackSampleRate
are integer between 0-100.
Archive Policy
Message archiving provides the ability to archive a single copy of all messages published to your topic. You can store published messages within your topic by enabling the message archive policy on the topic, which enables message archiving for all subscriptions linked to that topic. Messages can be archived for a minimum of one day to a maximum of 365 days.
Example with an archive policy:
var topic = new Topic(this, "MyTopic", new TopicProps {
Fifo = true,
MessageRetentionPeriodInDays = 7
});
Note: The messageRetentionPeriodInDays
property is only available for FIFO topics.
TracingConfig
Tracing mode of an Amazon SNS topic.
If PassThrough, the topic passes trace headers received from the Amazon SNS publisher to its subscription. If set to Active, Amazon SNS will vend X-Ray segment data to topic owner account if the sampled flag in the tracing header is true.
The default TracingConfig is TracingConfig.PASS_THROUGH
.
Example with a tracingConfig set to Active:
var topic = new Topic(this, "MyTopic", new TopicProps {
TracingConfig = TracingConfig.ACTIVE
});
Classes
BetweenCondition | Between condition for a numeric attribute. |
CfnSubscription | The |
CfnSubscriptionProps | Properties for defining a |
CfnTopic | The |
CfnTopic.LoggingConfigProperty | The |
CfnTopic.SubscriptionProperty |
|
CfnTopicInlinePolicy | The |
CfnTopicInlinePolicyProps | Properties for defining a |
CfnTopicPolicy | The |
CfnTopicPolicyProps | Properties for defining a |
CfnTopicProps | Properties for defining a |
Filter | Filter implementation of FilterOrPolicy. |
FilterOrPolicy | Class for building the FilterPolicy by avoiding union types. |
FilterOrPolicyType | The type of the MessageBody at a given key value pair. |
LoggingConfig | A logging configuration for delivery status of messages sent from SNS topic to subscribed endpoints. |
LoggingProtocol | The type of supported protocol for delivery status logging. |
NumericConditions | Conditions that can be applied to numeric attributes. |
Policy | Policy Implementation of FilterOrPolicy. |
StringConditions | Conditions that can be applied to string attributes. |
Subscription | A new subscription. |
SubscriptionFilter | A subscription filter for an attribute. |
SubscriptionOptions | Options for creating a new subscription. |
SubscriptionProps | Properties for creating a new subscription. |
SubscriptionProtocol | The type of subscription, controlling the type of the endpoint parameter. |
Topic | A new SNS topic. |
TopicAttributes | Represents an SNS topic defined outside of this stack. |
TopicBase | Either a new or imported Topic. |
TopicPolicy | The policy for an SNS Topic. |
TopicPolicyProps | Properties to associate SNS topics with a policy. |
TopicProps | Properties for a new SNS topic. |
TopicSubscriptionConfig | Subscription configuration. |
TracingConfig | The tracing mode of an Amazon SNS topic. |
Interfaces
CfnTopic.ILoggingConfigProperty | The |
CfnTopic.ISubscriptionProperty |
|
IBetweenCondition | Between condition for a numeric attribute. |
ICfnSubscriptionProps | Properties for defining a |
ICfnTopicInlinePolicyProps | Properties for defining a |
ICfnTopicPolicyProps | Properties for defining a |
ICfnTopicProps | Properties for defining a |
ILoggingConfig | A logging configuration for delivery status of messages sent from SNS topic to subscribed endpoints. |
INumericConditions | Conditions that can be applied to numeric attributes. |
IStringConditions | Conditions that can be applied to string attributes. |
ISubscriptionOptions | Options for creating a new subscription. |
ISubscriptionProps | Properties for creating a new subscription. |
ITopic | Represents an SNS topic. |
ITopicAttributes | Represents an SNS topic defined outside of this stack. |
ITopicPolicyProps | Properties to associate SNS topics with a policy. |
ITopicProps | Properties for a new SNS topic. |
ITopicSubscription | Topic subscription. |
ITopicSubscriptionConfig | Subscription configuration. |