Amazon Simple Notification Service Construct Library
Add an SNS Topic to your stack:
const topic = new sns.Topic(this, 'Topic', {
displayName: 'Customer subscription topic',
});
topic = sns.Topic(self, "Topic",
display_name="Customer subscription topic"
)
Topic topic = Topic.Builder.create(this, "Topic")
.displayName("Customer subscription topic")
.build();
var topic = new Topic(this, "Topic", new TopicProps {
DisplayName = "Customer subscription topic"
});
topic := sns.NewTopic(this, jsii.String("Topic"), &TopicProps{
DisplayName: jsii.String("Customer subscription topic"),
})
Add a FIFO SNS topic with content-based de-duplication to your stack:
const topic = new sns.Topic(this, 'Topic', {
contentBasedDeduplication: true,
displayName: 'Customer subscription topic',
fifo: true,
});
topic = sns.Topic(self, "Topic",
content_based_deduplication=True,
display_name="Customer subscription topic",
fifo=True
)
Topic topic = Topic.Builder.create(this, "Topic")
.contentBasedDeduplication(true)
.displayName("Customer subscription topic")
.fifo(true)
.build();
var topic = new Topic(this, "Topic", new TopicProps {
ContentBasedDeduplication = true,
DisplayName = "Customer subscription topic",
Fifo = true
});
topic := sns.NewTopic(this, jsii.String("Topic"), &TopicProps{
ContentBasedDeduplication: jsii.Boolean(true),
DisplayName: jsii.String("Customer subscription topic"),
Fifo: jsii.Boolean(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).
const topic = new sns.Topic(this, 'Topic', {
signatureVersion: '2',
});
topic = sns.Topic(self, "Topic",
signature_version="2"
)
Topic topic = Topic.Builder.create(this, "Topic")
.signatureVersion("2")
.build();
var topic = new Topic(this, "Topic", new TopicProps {
SignatureVersion = "2"
});
topic := sns.NewTopic(this, jsii.String("Topic"), &TopicProps{
SignatureVersion: jsii.String("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:
const myTopic = new sns.Topic(this, 'MyTopic');
myTopic.addSubscription(new subscriptions.UrlSubscription('https://foobar.com/'));
my_topic = sns.Topic(self, "MyTopic")
my_topic.add_subscription(subscriptions.UrlSubscription("https://foobar.com/"))
Topic myTopic = new Topic(this, "MyTopic");
myTopic.addSubscription(new UrlSubscription("https://foobar.com/"));
var myTopic = new Topic(this, "MyTopic");
myTopic.AddSubscription(new UrlSubscription("https://foobar.com/"));
myTopic := sns.NewTopic(this, jsii.String("MyTopic"))
myTopic.AddSubscription(subscriptions.NewUrlSubscription(jsii.String("https://foobar.com/")))
Subscribe a queue to the topic:
declare const queue: sqs.Queue;
const myTopic = new sns.Topic(this, 'MyTopic');
myTopic.addSubscription(new subscriptions.SqsSubscription(queue));
# queue: sqs.Queue
my_topic = sns.Topic(self, "MyTopic")
my_topic.add_subscription(subscriptions.SqsSubscription(queue))
Queue queue;
Topic myTopic = new Topic(this, "MyTopic");
myTopic.addSubscription(new SqsSubscription(queue));
Queue queue;
var myTopic = new Topic(this, "MyTopic");
myTopic.AddSubscription(new SqsSubscription(queue));
var queue Queue
myTopic := sns.NewTopic(this, jsii.String("MyTopic"))
myTopic.AddSubscription(subscriptions.NewSqsSubscription(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.
declare const accountPrincipal: iam.AccountPrincipal;
const myTopic = new sns.Topic(this, 'MyTopic');
myTopic.grants.subscribe(accountPrincipal);
# account_principal: iam.AccountPrincipal
my_topic = sns.Topic(self, "MyTopic")
my_topic.grants.subscribe(account_principal)
AccountPrincipal accountPrincipal;
Topic myTopic = new Topic(this, "MyTopic");
myTopic.grants.subscribe(accountPrincipal);
AccountPrincipal accountPrincipal;
var myTopic = new Topic(this, "MyTopic");
myTopic.Grants.Subscribe(accountPrincipal);
var accountPrincipal AccountPrincipal
myTopic := sns.NewTopic(this, jsii.String("MyTopic"))
myTopic.Grants.Subscribe(accountPrincipal)
Filter policy
A filter policy can be specified when subscribing an endpoint to a topic.
Example with a Lambda subscription:
import * as lambda from 'aws-cdk-lib/aws-lambda';
const myTopic = new sns.Topic(this, 'MyTopic');
declare const fn: lambda.Function;
// 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 subscriptions.LambdaSubscription(fn, {
filterPolicy: {
color: sns.SubscriptionFilter.stringFilter({
allowlist: ['red', 'orange'],
matchPrefixes: ['bl'],
matchSuffixes: ['ue'],
}),
size: sns.SubscriptionFilter.stringFilter({
denylist: ['small', 'medium'],
}),
price: sns.SubscriptionFilter.numericFilter({
between: { start: 100, stop: 200 },
greaterThan: 300,
}),
store: sns.SubscriptionFilter.existsFilter(),
},
}));
import aws_cdk.aws_lambda as lambda_
# fn: lambda.Function
my_topic = sns.Topic(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(subscriptions.LambdaSubscription(fn,
filter_policy={
"color": sns.SubscriptionFilter.string_filter(
allowlist=["red", "orange"],
match_prefixes=["bl"],
match_suffixes=["ue"]
),
"size": sns.SubscriptionFilter.string_filter(
denylist=["small", "medium"]
),
"price": sns.SubscriptionFilter.numeric_filter(
between=sns.BetweenCondition(start=100, stop=200),
greater_than=300
),
"store": sns.SubscriptionFilter.exists_filter()
}
))
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());
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() }
}
}));
import lambda "github.com/aws/aws-cdk-go/awscdk"
var fn Function
myTopic := sns.NewTopic(this, jsii.String("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(subscriptions.NewLambdaSubscription(fn, &LambdaSubscriptionProps{
FilterPolicy: map[string]SubscriptionFilter{
"color": sns.SubscriptionFilter_stringFilter(&StringConditions{
"allowlist": []*string{
jsii.String("red"),
jsii.String("orange"),
},
"matchPrefixes": []*string{
jsii.String("bl"),
},
"matchSuffixes": []*string{
jsii.String("ue"),
},
}),
"size": sns.SubscriptionFilter_stringFilter(&StringConditions{
"denylist": []*string{
jsii.String("small"),
jsii.String("medium"),
},
}),
"price": sns.SubscriptionFilter_numericFilter(&NumericConditions{
"between": &BetweenCondition{
"start": jsii.Number(100),
"stop": jsii.Number(200),
},
"greaterThan": jsii.Number(300),
}),
"store": sns.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:
import * as lambda from 'aws-cdk-lib/aws-lambda';
const myTopic = new sns.Topic(this, 'MyTopic');
declare const fn: lambda.Function;
// Lambda should receive only message matching the following conditions on message body:
// color: 'red' or 'orange'
// store: property must not be present
myTopic.addSubscription(new subscriptions.LambdaSubscription(fn, {
filterPolicyWithMessageBody: {
background: sns.FilterOrPolicy.policy({
color: sns.FilterOrPolicy.filter(sns.SubscriptionFilter.stringFilter({
allowlist: ['red', 'orange'],
})),
}),
store: sns.FilterOrPolicy.filter(sns.SubscriptionFilter.notExistsFilter()),
},
}));
import aws_cdk.aws_lambda as lambda_
# fn: lambda.Function
my_topic = sns.Topic(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(subscriptions.LambdaSubscription(fn,
filter_policy_with_message_body={
"background": sns.FilterOrPolicy.policy({
"color": sns.FilterOrPolicy.filter(sns.SubscriptionFilter.string_filter(
allowlist=["red", "orange"]
))
}),
"store": sns.FilterOrPolicy.filter(sns.SubscriptionFilter.not_exists_filter())
}
))
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'
// store: property must not be present
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())))),
"store", FilterOrPolicy.filter(SubscriptionFilter.notExistsFilter())))
.build());
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'
// store: property must not be present
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" }
})) }
}) },
{ "store", FilterOrPolicy.Filter(SubscriptionFilter.NotExistsFilter()) }
}
}));
import lambda "github.com/aws/aws-cdk-go/awscdk"
var fn Function
myTopic := sns.NewTopic(this, jsii.String("MyTopic"))
// Lambda should receive only message matching the following conditions on message body:
// color: 'red' or 'orange'
// store: property must not be present
myTopic.AddSubscription(subscriptions.NewLambdaSubscription(fn, &LambdaSubscriptionProps{
FilterPolicyWithMessageBody: map[string]FilterOrPolicy{
"background": sns.FilterOrPolicy_policy(map[string]FilterOrPolicy{
"color": sns.FilterOrPolicy_filter(sns.SubscriptionFilter_stringFilter(&StringConditions{
"allowlist": []*string{
jsii.String("red"),
jsii.String("orange"),
},
})),
}),
"store": sns.FilterOrPolicy_filter(sns.SubscriptionFilter_notExistsFilter()),
},
}))
Example of Firehose Subscription
import * as firehose from 'aws-cdk-lib/aws-kinesisfirehose';
const topic = new sns.Topic(this, 'Topic');
declare const stream: firehose.DeliveryStream;
new sns.Subscription(this, 'Subscription', {
topic,
endpoint: stream.deliveryStreamArn,
protocol: sns.SubscriptionProtocol.FIREHOSE,
subscriptionRoleArn: "SAMPLE_ARN", //role with permissions to send messages to a firehose delivery stream
});
import aws_cdk.aws_kinesisfirehose as firehose
# stream: firehose.DeliveryStream
topic = sns.Topic(self, "Topic")
sns.Subscription(self, "Subscription",
topic=topic,
endpoint=stream.delivery_stream_arn,
protocol=sns.SubscriptionProtocol.FIREHOSE,
subscription_role_arn="SAMPLE_ARN"
)
import software.amazon.awscdk.services.kinesisfirehose.*;
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();
using Amazon.CDK.AWS.KinesisFirehose;
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"
});
import firehose "github.com/aws/aws-cdk-go/awscdk"
var stream DeliveryStream
topic := sns.NewTopic(this, jsii.String("Topic"))
sns.NewSubscription(this, jsii.String("Subscription"), &SubscriptionProps{
Topic: Topic,
Endpoint: stream.deliveryStreamArn,
Protocol: sns.SubscriptionProtocol_FIREHOSE,
SubscriptionRoleArn: jsii.String("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.
const topic = new sns.Topic(this, 'Topic');
const dlQueue = new sqs.Queue(this, 'DeadLetterQueue', {
queueName: 'MySubscription_DLQ',
retentionPeriod: Duration.days(14),
});
new sns.Subscription(this, 'Subscription', {
endpoint: 'endpoint',
protocol: sns.SubscriptionProtocol.LAMBDA,
topic,
deadLetterQueue: dlQueue,
});
topic = sns.Topic(self, "Topic")
dl_queue = sqs.Queue(self, "DeadLetterQueue",
queue_name="MySubscription_DLQ",
retention_period=Duration.days(14)
)
sns.Subscription(self, "Subscription",
endpoint="endpoint",
protocol=sns.SubscriptionProtocol.LAMBDA,
topic=topic,
dead_letter_queue=dl_queue
)
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();
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
});
topic := sns.NewTopic(this, jsii.String("Topic"))
dlQueue := sqs.NewQueue(this, jsii.String("DeadLetterQueue"), &QueueProps{
QueueName: jsii.String("MySubscription_DLQ"),
RetentionPeriod: awscdk.Duration_Days(jsii.Number(14)),
})
sns.NewSubscription(this, jsii.String("Subscription"), &SubscriptionProps{
Endpoint: jsii.String("endpoint"),
Protocol: sns.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:
import * as codecommit from 'aws-cdk-lib/aws-codecommit';
import * as targets from 'aws-cdk-lib/aws-events-targets';
declare const repo: codecommit.Repository;
const myTopic = new sns.Topic(this, 'Topic');
repo.onCommit('OnCommit', {
target: new targets.SnsTopic(myTopic),
});
import aws_cdk.aws_codecommit as codecommit
import aws_cdk.aws_events_targets as targets
# repo: codecommit.Repository
my_topic = sns.Topic(self, "Topic")
repo.on_commit("OnCommit",
target=targets.SnsTopic(my_topic)
)
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());
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)
});
import codecommit "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"
var repo Repository
myTopic := sns.NewTopic(this, jsii.String("Topic"))
repo.onCommit(jsii.String("OnCommit"), &OnCommitOptions{
Target: targets.NewSnsTopic(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.
const topic = new sns.Topic(this, 'Topic');
const topicPolicy = new sns.TopicPolicy(this, 'TopicPolicy', {
topics: [topic],
});
topicPolicy.document.addStatements(new iam.PolicyStatement({
actions: ["sns:Subscribe"],
principals: [new iam.AnyPrincipal()],
resources: [topic.topicArn],
}));
topic = sns.Topic(self, "Topic")
topic_policy = sns.TopicPolicy(self, "TopicPolicy",
topics=[topic]
)
topic_policy.document.add_statements(iam.PolicyStatement(
actions=["sns:Subscribe"],
principals=[iam.AnyPrincipal()],
resources=[topic.topic_arn]
))
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());
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 }
}));
topic := sns.NewTopic(this, jsii.String("Topic"))
topicPolicy := sns.NewTopicPolicy(this, jsii.String("TopicPolicy"), &TopicPolicyProps{
Topics: []ITopic{
topic,
},
})
topicPolicy.Document.AddStatements(iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("sns:Subscribe"),
},
Principals: []IPrincipal{
iam.NewAnyPrincipal(),
},
Resources: []*string{
topic.topicArn,
},
}))
A policy document can also be passed on TopicPolicy construction
const topic = new sns.Topic(this, 'Topic');
const policyDocument = new iam.PolicyDocument({
assignSids: true,
statements: [
new iam.PolicyStatement({
actions: ["sns:Subscribe"],
principals: [new iam.AnyPrincipal()],
resources: [topic.topicArn],
}),
],
});
const topicPolicy = new sns.TopicPolicy(this, 'Policy', {
topics: [topic],
policyDocument,
});
topic = sns.Topic(self, "Topic")
policy_document = iam.PolicyDocument(
assign_sids=True,
statements=[
iam.PolicyStatement(
actions=["sns:Subscribe"],
principals=[iam.AnyPrincipal()],
resources=[topic.topic_arn]
)
]
)
topic_policy = sns.TopicPolicy(self, "Policy",
topics=[topic],
policy_document=policy_document
)
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();
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
});
topic := sns.NewTopic(this, jsii.String("Topic"))
policyDocument := iam.NewPolicyDocument(&PolicyDocumentProps{
AssignSids: jsii.Boolean(true),
Statements: []PolicyStatement{
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("sns:Subscribe"),
},
Principals: []IPrincipal{
iam.NewAnyPrincipal(),
},
Resources: []*string{
topic.topicArn,
},
}),
},
})
topicPolicy := sns.NewTopicPolicy(this, jsii.String("Policy"), &TopicPolicyProps{
Topics: []ITopic{
topic,
},
PolicyDocument: PolicyDocument,
})
A simpler and more general way of achieving the same result is to use the TopicGrants class:
const topic = new sns.Topic(this, 'Topic');
// This would work the same way if topic was a CfnTopic (L1)
sns.TopicGrants.fromTopic(topic).subscribe(new iam.AnyPrincipal());
topic = sns.Topic(self, "Topic")
# This would work the same way if topic was a CfnTopic (L1)
sns.TopicGrants.from_topic(topic).subscribe(iam.AnyPrincipal())
Topic topic = new Topic(this, "Topic");
// This would work the same way if topic was a CfnTopic (L1)
TopicGrants.fromTopic(topic).subscribe(new AnyPrincipal());
var topic = new Topic(this, "Topic");
// This would work the same way if topic was a CfnTopic (L1)
TopicGrants.FromTopic(topic).Subscribe(new AnyPrincipal());
topic := sns.NewTopic(this, jsii.String("Topic"))
// This would work the same way if topic was a CfnTopic (L1)
sns.TopicGrants_FromTopic(topic).Subscribe(iam.NewAnyPrincipal())
For convenience, if you are using an L2, you can also call grants on the topic:
const topic = new sns.Topic(this, 'Topic');
topic.grants.subscribe(new iam.AnyPrincipal());
topic = sns.Topic(self, "Topic")
topic.grants.subscribe(iam.AnyPrincipal())
Topic topic = new Topic(this, "Topic");
topic.grants.subscribe(new AnyPrincipal());
var topic = new Topic(this, "Topic");
topic.Grants.Subscribe(new AnyPrincipal());
topic := sns.NewTopic(this, jsii.String("Topic"))
topic.Grants.Subscribe(iam.NewAnyPrincipal())
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:
const topic = new sns.Topic(this, 'Topic');
const policyDocument = new iam.PolicyDocument({
assignSids: true,
statements: [
new iam.PolicyStatement({
actions: ["sns:Publish"],
principals: [new iam.ServicePrincipal('s3.amazonaws.com')],
resources: [topic.topicArn],
}),
],
});
const topicPolicy = new sns.TopicPolicy(this, 'Policy', {
topics: [topic],
policyDocument,
enforceSSL: true,
});
topic = sns.Topic(self, "Topic")
policy_document = iam.PolicyDocument(
assign_sids=True,
statements=[
iam.PolicyStatement(
actions=["sns:Publish"],
principals=[iam.ServicePrincipal("s3.amazonaws.com")],
resources=[topic.topic_arn]
)
]
)
topic_policy = sns.TopicPolicy(self, "Policy",
topics=[topic],
policy_document=policy_document,
enforce_ssl=True
)
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();
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
});
topic := sns.NewTopic(this, jsii.String("Topic"))
policyDocument := iam.NewPolicyDocument(&PolicyDocumentProps{
AssignSids: jsii.Boolean(true),
Statements: []PolicyStatement{
iam.NewPolicyStatement(&PolicyStatementProps{
Actions: []*string{
jsii.String("sns:Publish"),
},
Principals: []IPrincipal{
iam.NewServicePrincipal(jsii.String("s3.amazonaws.com")),
},
Resources: []*string{
topic.topicArn,
},
}),
},
})
topicPolicy := sns.NewTopicPolicy(this, jsii.String("Policy"), &TopicPolicyProps{
Topics: []ITopic{
topic,
},
PolicyDocument: PolicyDocument,
EnforceSSL: jsii.Boolean(true),
})
Similiarly you can enforce SSL by setting the enforceSSL flag on the topic:
const topic = new sns.Topic(this, 'TopicAddPolicy', {
enforceSSL: true,
});
topic.addToResourcePolicy(new iam.PolicyStatement({
principals: [new iam.ServicePrincipal('s3.amazonaws.com')],
actions: ['sns:Publish'],
resources: [topic.topicArn],
}));
topic = sns.Topic(self, "TopicAddPolicy",
enforce_ssl=True
)
topic.add_to_resource_policy(iam.PolicyStatement(
principals=[iam.ServicePrincipal("s3.amazonaws.com")],
actions=["sns:Publish"],
resources=[topic.topic_arn]
))
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());
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 }
}));
topic := sns.NewTopic(this, jsii.String("TopicAddPolicy"), &TopicProps{
EnforceSSL: jsii.Boolean(true),
})
topic.AddToResourcePolicy(iam.NewPolicyStatement(&PolicyStatementProps{
Principals: []IPrincipal{
iam.NewServicePrincipal(jsii.String("s3.amazonaws.com")),
},
Actions: []*string{
jsii.String("sns:Publish"),
},
Resources: []*string{
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:
- HTTP
- Amazon Data Firehose
- AWS Lambda
- Platform application endpoint
- Amazon Simple Queue Service
Example with a delivery status logging configuration for SQS:
declare const role: iam.Role;
const topic = new sns.Topic(this, 'MyTopic', {
loggingConfigs: [
{
protocol: sns.LoggingProtocol.SQS,
failureFeedbackRole: role,
successFeedbackRole: role,
successFeedbackSampleRate: 50,
},
],
});
# role: iam.Role
topic = sns.Topic(self, "MyTopic",
logging_configs=[sns.LoggingConfig(
protocol=sns.LoggingProtocol.SQS,
failure_feedback_role=role,
success_feedback_role=role,
success_feedback_sample_rate=50
)
]
)
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();
Role role;
var topic = new Topic(this, "MyTopic", new TopicProps {
LoggingConfigs = new [] { new LoggingConfig {
Protocol = LoggingProtocol.SQS,
FailureFeedbackRole = role,
SuccessFeedbackRole = role,
SuccessFeedbackSampleRate = 50
} }
});
var role Role
topic := sns.NewTopic(this, jsii.String("MyTopic"), &TopicProps{
LoggingConfigs: []LoggingConfig{
&LoggingConfig{
Protocol: sns.LoggingProtocol_SQS,
FailureFeedbackRole: role,
SuccessFeedbackRole: role,
SuccessFeedbackSampleRate: jsii.Number(50),
},
},
})
A delivery status logging configuration can also be added to your topic by addLoggingConfig method:
declare const role: iam.Role;
const topic = new sns.Topic(this, 'MyTopic');
topic.addLoggingConfig({
protocol: sns.LoggingProtocol.SQS,
failureFeedbackRole: role,
successFeedbackRole: role,
successFeedbackSampleRate: 50,
});
# role: iam.Role
topic = sns.Topic(self, "MyTopic")
topic.add_logging_config(
protocol=sns.LoggingProtocol.SQS,
failure_feedback_role=role,
success_feedback_role=role,
success_feedback_sample_rate=50
)
Role role;
Topic topic = new Topic(this, "MyTopic");
topic.addLoggingConfig(LoggingConfig.builder()
.protocol(LoggingProtocol.SQS)
.failureFeedbackRole(role)
.successFeedbackRole(role)
.successFeedbackSampleRate(50)
.build());
Role role;
var topic = new Topic(this, "MyTopic");
topic.AddLoggingConfig(new LoggingConfig {
Protocol = LoggingProtocol.SQS,
FailureFeedbackRole = role,
SuccessFeedbackRole = role,
SuccessFeedbackSampleRate = 50
});
var role Role
topic := sns.NewTopic(this, jsii.String("MyTopic"))
topic.AddLoggingConfig(&LoggingConfig{
Protocol: sns.LoggingProtocol_SQS,
FailureFeedbackRole: role,
SuccessFeedbackRole: role,
SuccessFeedbackSampleRate: jsii.Number(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:
const topic = new sns.Topic(this, 'MyTopic', {
fifo: true,
messageRetentionPeriodInDays: 7,
});
topic = sns.Topic(self, "MyTopic",
fifo=True,
message_retention_period_in_days=7
)
Topic topic = Topic.Builder.create(this, "MyTopic")
.fifo(true)
.messageRetentionPeriodInDays(7)
.build();
var topic = new Topic(this, "MyTopic", new TopicProps {
Fifo = true,
MessageRetentionPeriodInDays = 7
});
topic := sns.NewTopic(this, jsii.String("MyTopic"), &TopicProps{
Fifo: jsii.Boolean(true),
MessageRetentionPeriodInDays: jsii.Number(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:
const topic = new sns.Topic(this, 'MyTopic', {
tracingConfig: sns.TracingConfig.ACTIVE,
});
topic = sns.Topic(self, "MyTopic",
tracing_config=sns.TracingConfig.ACTIVE
)
Topic topic = Topic.Builder.create(this, "MyTopic")
.tracingConfig(TracingConfig.ACTIVE)
.build();
var topic = new Topic(this, "MyTopic", new TopicProps {
TracingConfig = TracingConfig.ACTIVE
});
topic := sns.NewTopic(this, jsii.String("MyTopic"), &TopicProps{
TracingConfig: sns.TracingConfig_ACTIVE,
})
High-throughput mode for Amazon SNS FIFO Topics
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 fifoThroughputScope property:
const topic = new sns.Topic(this, 'MyTopic', {
fifo: true,
fifoThroughputScope: sns.FifoThroughputScope.TOPIC,
});
topic = sns.Topic(self, "MyTopic",
fifo=True,
fifo_throughput_scope=sns.FifoThroughputScope.TOPIC
)
Topic topic = Topic.Builder.create(this, "MyTopic")
.fifo(true)
.fifoThroughputScope(FifoThroughputScope.TOPIC)
.build();
var topic = new Topic(this, "MyTopic", new TopicProps {
Fifo = true,
FifoThroughputScope = FifoThroughputScope.TOPIC
});
topic := sns.NewTopic(this, jsii.String("MyTopic"), &TopicProps{
Fifo: jsii.Boolean(true),
FifoThroughputScope: sns.FifoThroughputScope_TOPIC,
})
Note: The fifoThroughputScope property is only available for FIFO topics.
Types
| Name | Kind | Summary |
|---|---|---|
Subscription | Construct (L2) | A new subscription. |
Topic | Construct (L2) | A new SNS topic. |
TopicBase | Construct (L2) | Either a new or imported Topic. |
TopicPolicy | Construct (L2) | The policy for an SNS Topic. |
CfnSubscription | Construct (L1) | The AWS::SNS::Subscription resource subscribes an endpoint to an Amazon topic. |
CfnTopic | Construct (L1) | The AWS::SNS::Topic resource creates a topic to which notifications can be published. |
CfnTopicInlinePolicy | Construct (L1) | The AWS::SNS::TopicInlinePolicy resource associates one Amazon topic with one policy. |
CfnTopicPolicy | Construct (L1) | The AWS::SNS::TopicPolicy resource associates Amazon topics with a policy. |
BackoffFunction | Enum | Algorithms which can be used by SNS to calculate the delays associated with all of the retry attempts between the first and last retries in the backoff phase. |
BetweenCondition | Struct | Between condition for a numeric attribute. |
CfnSubscriptionProps | Struct | Properties for defining a CfnSubscription. |
CfnTopic.LoggingConfigProperty | Struct | The LoggingConfig property type specifies the Delivery status logging configuration for an AWS::SNS::Topic . |
CfnTopic.SubscriptionProperty | Struct | Subscription is an embedded property that describes the subscription endpoints of an Amazon topic. |
CfnTopicInlinePolicyProps | Struct | Properties for defining a CfnTopicInlinePolicy. |
CfnTopicPolicyProps | Struct | Properties for defining a CfnTopicPolicy. |
CfnTopicProps | Struct | Properties for defining a CfnTopic. |
DeliveryPolicy | Struct | Options for customising the delivery of SNS messages to HTTP/S endpoints. |
FifoThroughputScope | Enum | The throughput quota and deduplication behavior to apply for the FIFO topic. |
Filter | Class | Filter implementation of FilterOrPolicy. |
FilterOrPolicy | Class | Class for building the FilterPolicy by avoiding union types. |
FilterOrPolicyType | Enum | The type of the MessageBody at a given key value pair. |
HealthyRetryPolicy | Struct | Options for customising the retry policy of the delivery of SNS messages to HTTP/S endpoints. |
ITopic | Interface | Represents an SNS topic. |
ITopicSubscription | Interface | Topic subscription. |
LoggingConfig | Struct | A logging configuration for delivery status of messages sent from SNS topic to subscribed endpoints. |
LoggingProtocol | Enum | The type of supported protocol for delivery status logging. |
NumericConditions | Struct | Conditions that can be applied to numeric attributes. |
Policy | Class | Policy Implementation of FilterOrPolicy. |
RequestPolicy | Struct | Options for customising aspects of the content sent in AWS SNS HTTP/S requests. |
StringConditions | Struct | Conditions that can be applied to string attributes. |
SubscriptionFilter | Class | A subscription filter for an attribute. |
SubscriptionOptions | Struct | Options for creating a new subscription. |
SubscriptionProps | Struct | Properties for creating a new subscription. |
SubscriptionProtocol | Enum | The type of subscription, controlling the type of the endpoint parameter. |
ThrottlePolicy | Struct | Options for customising AWS SNS HTTP/S delivery throttling. |
TopicAttributes | Struct | Represents an SNS topic defined outside of this stack. |
TopicGrants | Facade | Collection of grant methods for a ITopicRef. |
TopicPolicyProps | Struct | Properties to associate SNS topics with a policy. |
TopicProps | Struct | Properties for a new SNS topic. |
TopicSubscriptionConfig | Struct | Subscription configuration. |
TracingConfig | Enum | The tracing mode of an Amazon SNS topic. |