Amazon Simple Notification Service (SNS) is a fully managed messaging service that enables you to send notifications to multiple subscribers. These subscribers can be email addresses, phone numbers, or other endpoints such as Amazon SQS queues and Lambda functions. One of the core concepts in SNS is subscriptions, which define how messages are delivered to these endpoints.
In this tutorial, we will explore what SNS subscriptions are, how they work, and how you can manage them using AWS CLI and SDKs. By the end of this guide, you should have a solid understanding of how to set up and manage subscriptions for your SNS topics.
An SNS subscription is a relationship between an SNS topic and an endpoint that specifies how messages published to the topic should be delivered. Each subscription has several attributes, including:
Subscriptions can be confirmed by the endpoint. For example, when you create an email subscription, AWS SNS sends a confirmation email to the specified address. The user must open this email and confirm the subscription before messages are delivered.
To create a subscription using the AWS Command Line Interface (CLI), follow these steps:
Create an SNS Topic: If you haven't already, create an SNS topic.
aws sns create-topic --name MyTopic
{
"TopicArn": "arn:aws:sns:us-east-1:123456789012:MyTopic"
}Create a Subscription: Subscribe an endpoint to the topic.
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic --protocol email --notification-endpoint example@example.com
{
"SubscriptionArn": "pending confirmation"
}Note that the subscription ARN will be in a "pending confirmation" state until the user confirms the subscription via email.
Confirm the Subscription: Check your inbox and confirm the subscription by clicking the link in the confirmation email.
You can also manage subscriptions using the AWS SDK for JavaScript. Below is an example of how to list all subscriptions for a topic:
1const AWS = require('aws-sdk');2AWS.config.region = 'us-east-1';34const sns = new AWS.SNS();56const params = {7TopicArn: 'arn:aws:sns:us-east-1:123456789012:MyTopic'8};910sns.listSubscriptionsByTopic(params, (err, data) => {11if (err) {12console.error('Error listing subscriptions:', err);13} else {14console.log('Subscriptions:', data.Subscriptions);15}16});
To delete a subscription, use the unsubscribe API in the AWS CLI or SDK.
1const params = {2SubscriptionArn: 'arn:aws:sns:us-east-1:123456789012:MyTopic:subscription-id'3};45sns.unsubscribe(params, (err, data) => {6if (err) {7console.error('Error deleting subscription:', err);8} else {9console.log('Subscription deleted successfully');10}11});
Now that you have a good understanding of SNS subscriptions, the next step is to explore Amazon SQS. SQS is another messaging service that can be used as an endpoint for SNS subscriptions. In the next tutorial, we will dive into how SQS works and how it integrates with SNS.
Stay tuned!