Skip to main content

The CDK Construct Library for AWS::SNS

Project description

Amazon Simple Notification Service Construct Library

---

End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.


Add an SNS Topic to your stack:

topic = sns.Topic(self, "Topic",
    display_name="Customer subscription topic"
)

Add a FIFO SNS topic with content-based de-duplication to your stack:

topic = sns.Topic(self, "Topic",
    content_based_deduplication=True,
    display_name="Customer subscription topic",
    fifo=True,
    topic_name="customerTopic"
)

Note that FIFO topics require a topic name to be provided. The required .fifo suffix will be automatically 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/aws-sns-subscriptions package:

Add an HTTPS Subscription to your topic:

my_topic = sns.Topic(self, "MyTopic")

my_topic.add_subscription(subscriptions.UrlSubscription("https://foobar.com/"))

Subscribe a queue to the topic:

# queue: sqs.Queue

my_topic = sns.Topic(self, "MyTopic")

my_topic.add_subscription(subscriptions.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:

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"]
        ),
        "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()
    }
))

Example of Firehose Subscription

from aws_cdk.aws_kinesisfirehose import DeliveryStream
# stream: 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"
)

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 = 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
)

CloudWatch Event Rule Target

SNS topics can be used as targets for CloudWatch event rules.

Use the @aws-cdk/aws-events-targets.SnsTopic:

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)
)

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 = 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]
))

A policy document can also be passed on TopicPolicy construction

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
)

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-sns-1.204.0.tar.gz (137.7 kB view details)

Uploaded Source

Built Distribution

aws_cdk.aws_sns-1.204.0-py3-none-any.whl (136.4 kB view details)

Uploaded Python 3

File details

Details for the file aws-cdk.aws-sns-1.204.0.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-sns-1.204.0.tar.gz
  • Upload date:
  • Size: 137.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.2

File hashes

Hashes for aws-cdk.aws-sns-1.204.0.tar.gz
Algorithm Hash digest
SHA256 5b70bea4eea0233658ee31c1fa9acb1177c8d7cc957e077d2f9a03d5d2ad1739
MD5 3436a8ed3bb12d198601d57bcc481fe7
BLAKE2b-256 f9fb480459a7564efe385824fd1f7fe169fe5fdd7b991c6a62c6b34d4dd775f0

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_sns-1.204.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_cdk.aws_sns-1.204.0-py3-none-any.whl
Algorithm Hash digest
SHA256 29e78a2494b6142fe818bea1c84a26ec0ba015dd5aba4a3c575dce9b497e5c63
MD5 1c1a2828df35bc9d7db5fa5e28af6aba
BLAKE2b-256 059736b109d75f6215fcf1c3f11ed009ec0112c2cb69b4637287412c7c4339df

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page