Package software.amazon.awscdk.services.sns
Amazon Simple Notification Service Construct Library
Add an SNS Topic to your stack:
Topic topic = Topic.Builder.create(this, "Topic") .displayName("Customer subscription topic") .build();
Add a FIFO SNS topic with content-based de-duplication to your stack:
Topic topic = Topic.Builder.create(this, "Topic") .contentBasedDeduplication(true) .displayName("Customer subscription topic") .fifo(true) .build();
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
).
Topic topic = Topic.Builder.create(this, "Topic") .signatureVersion("2") .build();
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:
Topic myTopic = new Topic(this, "MyTopic"); myTopic.addSubscription(new UrlSubscription("https://foobar.com/"));
Subscribe a queue to the topic:
Queue queue; Topic 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.
The grantSubscribe
method adds a policy statement to the topic's resource policy, allowing the specified principal to perform the sns:Subscribe
action.
It's useful when you want to allow entities, such as another AWS account or resources created later, to subscribe to the topic at their own pace, separating permission granting from the actual subscription process.
AccountPrincipal accountPrincipal; Topic myTopic = new Topic(this, "MyTopic"); myTopic.grantSubscribe(accountPrincipal);
Filter policy
A filter policy can be specified when subscribing an endpoint to a topic.
Example with a Lambda subscription:
import software.amazon.awscdk.services.lambda.*; Function fn; Topic 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(LambdaSubscription.Builder.create(fn) .filterPolicy(Map.of( "color", SubscriptionFilter.stringFilter(StringConditions.builder() .allowlist(List.of("red", "orange")) .matchPrefixes(List.of("bl")) .matchSuffixes(List.of("ue")) .build()), "size", SubscriptionFilter.stringFilter(StringConditions.builder() .denylist(List.of("small", "medium")) .build()), "price", SubscriptionFilter.numericFilter(NumericConditions.builder() .between(BetweenCondition.builder().start(100).stop(200).build()) .greaterThan(300) .build()), "store", SubscriptionFilter.existsFilter())) .build());
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:
import software.amazon.awscdk.services.lambda.*; Function fn; Topic myTopic = new Topic(this, "MyTopic"); // Lambda should receive only message matching the following conditions on message body: // color: 'red' or 'orange' myTopic.addSubscription(LambdaSubscription.Builder.create(fn) .filterPolicyWithMessageBody(Map.of( "background", FilterOrPolicy.policy(Map.of( "color", FilterOrPolicy.filter(SubscriptionFilter.stringFilter(StringConditions.builder() .allowlist(List.of("red", "orange")) .build())))))) .build());
Example of Firehose Subscription
import software.amazon.awscdk.services.kinesisfirehose.alpha.DeliveryStream; DeliveryStream stream; Topic topic = new Topic(this, "Topic"); Subscription.Builder.create(this, "Subscription") .topic(topic) .endpoint(stream.getDeliveryStreamArn()) .protocol(SubscriptionProtocol.FIREHOSE) .subscriptionRoleArn("SAMPLE_ARN") .build();
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.
Topic topic = new Topic(this, "Topic"); Queue dlQueue = Queue.Builder.create(this, "DeadLetterQueue") .queueName("MySubscription_DLQ") .retentionPeriod(Duration.days(14)) .build(); Subscription.Builder.create(this, "Subscription") .endpoint("endpoint") .protocol(SubscriptionProtocol.LAMBDA) .topic(topic) .deadLetterQueue(dlQueue) .build();
CloudWatch Event Rule Target
SNS topics can be used as targets for CloudWatch event rules.
Use the aws-cdk-lib/aws-events-targets.SnsTopic
:
import software.amazon.awscdk.services.codecommit.*; import software.amazon.awscdk.services.events.targets.*; Repository repo; Topic myTopic = new Topic(this, "Topic"); repo.onCommit("OnCommit", OnCommitOptions.builder() .target(new SnsTopic(myTopic)) .build());
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.
Topic topic = new Topic(this, "Topic"); TopicPolicy topicPolicy = TopicPolicy.Builder.create(this, "TopicPolicy") .topics(List.of(topic)) .build(); topicPolicy.document.addStatements(PolicyStatement.Builder.create() .actions(List.of("sns:Subscribe")) .principals(List.of(new AnyPrincipal())) .resources(List.of(topic.getTopicArn())) .build());
A policy document can also be passed on TopicPolicy
construction
Topic topic = new Topic(this, "Topic"); PolicyDocument policyDocument = PolicyDocument.Builder.create() .assignSids(true) .statements(List.of( PolicyStatement.Builder.create() .actions(List.of("sns:Subscribe")) .principals(List.of(new AnyPrincipal())) .resources(List.of(topic.getTopicArn())) .build())) .build(); TopicPolicy topicPolicy = TopicPolicy.Builder.create(this, "Policy") .topics(List.of(topic)) .policyDocument(policyDocument) .build();
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:
Topic topic = new Topic(this, "Topic"); PolicyDocument policyDocument = PolicyDocument.Builder.create() .assignSids(true) .statements(List.of( PolicyStatement.Builder.create() .actions(List.of("sns:Publish")) .principals(List.of(new ServicePrincipal("s3.amazonaws.com"))) .resources(List.of(topic.getTopicArn())) .build())) .build(); TopicPolicy topicPolicy = TopicPolicy.Builder.create(this, "Policy") .topics(List.of(topic)) .policyDocument(policyDocument) .enforceSSL(true) .build();
Similiarly you can enforce SSL by setting the enforceSSL
flag on the topic:
Topic topic = Topic.Builder.create(this, "TopicAddPolicy") .enforceSSL(true) .build(); topic.addToResourcePolicy(PolicyStatement.Builder.create() .principals(List.of(new ServicePrincipal("s3.amazonaws.com"))) .actions(List.of("sns:Publish")) .resources(List.of(topic.getTopicArn())) .build());
Delivery status logging
Amazon SNS provides support to log the delivery status of notification messages sent to topics with the following Amazon SNS endpoints:
- HTTP
- Amazon Kinesis Data Firehose
- AWS Lambda
- Platform application endpoint
- Amazon Simple Queue Service
Example with a delivery status logging configuration for SQS:
Role role; Topic topic = Topic.Builder.create(this, "MyTopic") .loggingConfigs(List.of(LoggingConfig.builder() .protocol(LoggingProtocol.SQS) .failureFeedbackRole(role) .successFeedbackRole(role) .successFeedbackSampleRate(50) .build())) .build();
A delivery status logging configuration can also be added to your topic by addLoggingConfig
method:
Role role; Topic topic = new Topic(this, "MyTopic"); topic.addLoggingConfig(LoggingConfig.builder() .protocol(LoggingProtocol.SQS) .failureFeedbackRole(role) .successFeedbackRole(role) .successFeedbackSampleRate(50) .build());
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:
Topic topic = Topic.Builder.create(this, "MyTopic") .fifo(true) .messageRetentionPeriodInDays(7) .build();
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:
Topic topic = Topic.Builder.create(this, "MyTopic") .tracingConfig(TracingConfig.ACTIVE) .build();
-
ClassDescriptionBetween condition for a numeric attribute.A builder for
BetweenCondition
An implementation forBetweenCondition
TheAWS::SNS::Subscription
resource subscribes an endpoint to an Amazon SNS topic.A fluent builder forCfnSubscription
.Properties for defining aCfnSubscription
.A builder forCfnSubscriptionProps
An implementation forCfnSubscriptionProps
TheAWS::SNS::Topic
resource creates a topic to which notifications can be published.A fluent builder forCfnTopic
.TheLoggingConfig
property type specifies theDelivery
status logging configuration for anAWS::SNS::Topic
.A builder forCfnTopic.LoggingConfigProperty
An implementation forCfnTopic.LoggingConfigProperty
Subscription
is an embedded property that describes the subscription endpoints of an Amazon SNS topic.A builder forCfnTopic.SubscriptionProperty
An implementation forCfnTopic.SubscriptionProperty
TheAWS::SNS::TopicInlinePolicy
resource associates one Amazon SNS topic with one policy.A fluent builder forCfnTopicInlinePolicy
.Properties for defining aCfnTopicInlinePolicy
.A builder forCfnTopicInlinePolicyProps
An implementation forCfnTopicInlinePolicyProps
TheAWS::SNS::TopicPolicy
resource associates Amazon SNS topics with a policy.A fluent builder forCfnTopicPolicy
.Properties for defining aCfnTopicPolicy
.A builder forCfnTopicPolicyProps
An implementation forCfnTopicPolicyProps
Properties for defining aCfnTopic
.A builder forCfnTopicProps
An implementation forCfnTopicProps
Filter implementation of FilterOrPolicy.Class for building the FilterPolicy by avoiding union types.The type of the MessageBody at a given key value pair.Represents an SNS topic.Internal default implementation forITopic
.A proxy class which represents a concrete javascript instance of this type.Topic subscription.Internal default implementation forITopicSubscription
.A proxy class which represents a concrete javascript instance of this type.A logging configuration for delivery status of messages sent from SNS topic to subscribed endpoints.A builder forLoggingConfig
An implementation forLoggingConfig
The type of supported protocol for delivery status logging.Conditions that can be applied to numeric attributes.A builder forNumericConditions
An implementation forNumericConditions
Policy Implementation of FilterOrPolicy.Conditions that can be applied to string attributes.A builder forStringConditions
An implementation forStringConditions
A new subscription.A fluent builder forSubscription
.A subscription filter for an attribute.Options for creating a new subscription.A builder forSubscriptionOptions
An implementation forSubscriptionOptions
Properties for creating a new subscription.A builder forSubscriptionProps
An implementation forSubscriptionProps
The type of subscription, controlling the type of the endpoint parameter.A new SNS topic.A fluent builder forTopic
.Represents an SNS topic defined outside of this stack.A builder forTopicAttributes
An implementation forTopicAttributes
Either a new or imported Topic.The policy for an SNS Topic.A fluent builder forTopicPolicy
.Properties to associate SNS topics with a policy.A builder forTopicPolicyProps
An implementation forTopicPolicyProps
Properties for a new SNS topic.A builder forTopicProps
An implementation forTopicProps
Subscription configuration.A builder forTopicSubscriptionConfig
An implementation forTopicSubscriptionConfig
The tracing mode of an Amazon SNS topic.