39 types
Add an SNS Topic to your stack:
topic = AWSCDK::SNS::Topic.new(self, "Topic", {
display_name: "Customer subscription topic",
})
Add a FIFO SNS topic with content-based de-duplication to your stack:
topic = AWSCDK::SNS::Topic.new(self, "Topic", {
content_based_deduplication: true,
display_name: "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).
topic = AWSCDK::SNS::Topic.new(self, "Topic", {
signature_version: "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.
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:
my_topic = AWSCDK::SNS::Topic.new(self, "MyTopic")
my_topic.add_subscription(AWSCDK::SNSSubscriptions::URLSubscription.new("https://foobar.com/"))
Subscribe a queue to the topic:
queue = nil # AWSCDK::SQS::Queue
my_topic = AWSCDK::SNS::Topic.new(self, "MyTopic")
my_topic.add_subscription(AWSCDK::SNSSubscriptions::SQSSubscription.new(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 topic.grants.subscribe 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.
account_principal = nil # AWSCDK::IAM::AccountPrincipal
my_topic = AWSCDK::SNS::Topic.new(self, "MyTopic")
my_topic.grants.subscribe(account_principal)
A filter policy can be specified when subscribing an endpoint to a topic.
Example with a Lambda subscription:
require 'aws-cdk-lib'
fn = nil # AWSCDK::Lambda::Function
my_topic = AWSCDK::SNS::Topic.new(self, "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
my_topic.add_subscription(AWSCDK::SNSSubscriptions::LambdaSubscription.new(fn, {
filter_policy: {
color: AWSCDK::SNS::SubscriptionFilter.string_filter({
allowlist: ["red", "orange"],
match_prefixes: ["bl"],
match_suffixes: ["ue"],
}),
size: AWSCDK::SNS::SubscriptionFilter.string_filter({
denylist: ["small", "medium"],
}),
price: AWSCDK::SNS::SubscriptionFilter.numeric_filter({
between: {start: 100, stop: 200},
greater_than: 300,
}),
store: AWSCDK::SNS::SubscriptionFilter.exists_filter,
},
}))
To filter messages based on the payload or body of the message, use the filter_policy_with_message_body property. This type of filter policy supports creating filters on nested objects.
Example with a Lambda subscription:
require 'aws-cdk-lib'
fn = nil # AWSCDK::Lambda::Function
my_topic = AWSCDK::SNS::Topic.new(self, "MyTopic")
# Lambda should receive only message matching the following conditions on message body:
# color: 'red' or 'orange'
# store: property must not be present
my_topic.add_subscription(AWSCDK::SNSSubscriptions::LambdaSubscription.new(fn, {
filter_policy_with_message_body: {
background: AWSCDK::SNS::FilterOrPolicy.policy({
color: AWSCDK::SNS::FilterOrPolicy.filter(AWSCDK::SNS::SubscriptionFilter.string_filter({
allowlist: ["red", "orange"],
})),
}),
store: AWSCDK::SNS::FilterOrPolicy.filter(AWSCDK::SNS::SubscriptionFilter.not_exists_filter),
},
}))
require 'aws-cdk-lib'
stream = nil # AWSCDK::KinesisFirehose::DeliveryStream
topic = AWSCDK::SNS::Topic.new(self, "Topic")
AWSCDK::SNS::Subscription.new(self, "Subscription", {
topic: topic,
endpoint: stream.delivery_stream_arn,
protocol: AWSCDK::SNS::SubscriptionProtocol::FIREHOSE,
subscription_role_arn: "SAMPLE_ARN",
})
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 = AWSCDK::SNS::Topic.new(self, "Topic")
dl_queue = AWSCDK::SQS::Queue.new(self, "DeadLetterQueue", {
queue_name: "MySubscription_DLQ",
retention_period: AWSCDK::Duration.days(14),
})
AWSCDK::SNS::Subscription.new(self, "Subscription", {
endpoint: "endpoint",
protocol: AWSCDK::SNS::SubscriptionProtocol::LAMBDA,
topic: topic,
dead_letter_queue: dl_queue,
})
SNS topics can be used as targets for CloudWatch event rules.
Use the aws-cdk-lib/aws-events-targets.SnsTopic:
require 'aws-cdk-lib'
repo = nil # AWSCDK::Codecommit::Repository
my_topic = AWSCDK::SNS::Topic.new(self, "Topic")
repo.on_commit("OnCommit", {
target: AWSCDK::EventsTargets::SNSTopic.new(my_topic),
})
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.
A topic policy is automatically created when add_to_resource_policy is called, if
one doesn't already exist. Using add_to_resource_policy is the simplest way to
add policies, but a TopicPolicy can also be created manually.
topic = AWSCDK::SNS::Topic.new(self, "Topic")
topic_policy = AWSCDK::SNS::TopicPolicy.new(self, "TopicPolicy", {
topics: [topic],
})
topic_policy.document.add_statements(AWSCDK::IAM::PolicyStatement.new({
actions: ["sns:Subscribe"],
principals: [AWSCDK::IAM::AnyPrincipal.new],
resources: [topic.topic_arn],
}))
A policy document can also be passed on TopicPolicy construction
topic = AWSCDK::SNS::Topic.new(self, "Topic")
policy_document = AWSCDK::IAM::PolicyDocument.new({
assign_sids: true,
statements: [
AWSCDK::IAM::PolicyStatement.new({
actions: ["sns:Subscribe"],
principals: [AWSCDK::IAM::AnyPrincipal.new],
resources: [topic.topic_arn],
}),
],
})
topic_policy = AWSCDK::SNS::TopicPolicy.new(self, "Policy", {
topics: [topic],
policy_document: policy_document,
})
A simpler and more general way of achieving the same result is to use the
TopicGrants class:
topic = AWSCDK::SNS::Topic.new(self, "Topic")
# This would work the same way if topic was a CfnTopic (L1)
AWSCDK::SNS::TopicGrants.from_topic(topic).subscribe(AWSCDK::IAM::AnyPrincipal.new)
For convenience, if you are using an L2, you can also call grants on the topic:
topic = AWSCDK::SNS::Topic.new(self, "Topic")
topic.grants.subscribe(AWSCDK::IAM::AnyPrincipal.new)
You can enforce SSL when creating a topic policy by setting the enforce_ssl flag:
topic = AWSCDK::SNS::Topic.new(self, "Topic")
policy_document = AWSCDK::IAM::PolicyDocument.new({
assign_sids: true,
statements: [
AWSCDK::IAM::PolicyStatement.new({
actions: ["sns:Publish"],
principals: [AWSCDK::IAM::ServicePrincipal.new("s3.amazonaws.com")],
resources: [topic.topic_arn],
}),
],
})
topic_policy = AWSCDK::SNS::TopicPolicy.new(self, "Policy", {
topics: [topic],
policy_document: policy_document,
enforce_ssl: true,
})
Similiarly you can enforce SSL by setting the enforce_ssl flag on the topic:
topic = AWSCDK::SNS::Topic.new(self, "TopicAddPolicy", {
enforce_ssl: true,
})
topic.add_to_resource_policy(AWSCDK::IAM::PolicyStatement.new({
principals: [AWSCDK::IAM::ServicePrincipal.new("s3.amazonaws.com")],
actions: ["sns:Publish"],
resources: [topic.topic_arn],
}))
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 = nil # AWSCDK::IAM::Role
topic = AWSCDK::SNS::Topic.new(self, "MyTopic", {
logging_configs: [
{
protocol: AWSCDK::SNS::LoggingProtocol::SQS,
failure_feedback_role: role,
success_feedback_role: role,
success_feedback_sample_rate: 50,
},
],
})
A delivery status logging configuration can also be added to your topic by add_logging_config method:
role = nil # AWSCDK::IAM::Role
topic = AWSCDK::SNS::Topic.new(self, "MyTopic")
topic.add_logging_config({
protocol: AWSCDK::SNS::LoggingProtocol::SQS,
failure_feedback_role: role,
success_feedback_role: role,
success_feedback_sample_rate: 50,
})
Note that valid values for success_feedback_sample_rate are integer between 0-100.
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 = AWSCDK::SNS::Topic.new(self, "MyTopic", {
fifo: true,
message_retention_period_in_days: 7,
})
Note: The message_retention_period_in_days property is only available for FIFO topics.
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 = AWSCDK::SNS::Topic.new(self, "MyTopic", {
tracing_config: AWSCDK::SNS::TracingConfig::ACTIVE,
})
High throughput FIFO topics in Amazon SNS efficiently manage high message throughput while maintaining strict message order, ensuring reliability and scalability for applications processing numerous messages. This solution is ideal for scenarios demanding both high throughput and ordered message delivery.
To improve message throughput using high throughput FIFO topics, increasing the number of message groups is recommended.
For more information, see High throughput FIFO topics in Amazon SNS.
You can configure high-throughput mode for your FIFO topics by setting the fifo_throughput_scope property:
topic = AWSCDK::SNS::Topic.new(self, "MyTopic", {
fifo: true,
fifo_throughput_scope: AWSCDK::SNS::FifoThroughputScope::TOPIC,
})
Note: The fifo_throughput_scope property is only available for FIFO topics.