How to Subscribe to an AWS SNS Topic: Step-by-Step Guide
To subscribe to an AWS SNS topic, use the
Subscribe API or AWS CLI command with the topic ARN and your endpoint (like email or HTTP). This creates a subscription that receives messages published to the topic after confirmation.Syntax
The basic syntax to subscribe to an SNS topic requires specifying the TopicArn, the Protocol (such as email, sms, http, https, lambda), and the Endpoint (the destination address or function).
For example, using AWS CLI:
aws sns subscribe --topic-arn <topic-arn> --protocol <protocol> --notification-endpoint <endpoint>
bash
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic --protocol email --notification-endpoint user@example.com
Example
This example shows how to subscribe an email address to an SNS topic using AWS CLI. After running the command, the user receives a confirmation email to accept the subscription.
bash
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic --protocol email --notification-endpoint user@example.com
Output
SubscriptionArn: pending confirmation
Common Pitfalls
- Not confirming the subscription: The subscription stays in "pending confirmation" until the user confirms via the endpoint (e.g., clicks the link in the email).
- Using wrong protocol or endpoint format: For example, using an invalid email or HTTP URL will cause subscription failure.
- Missing permissions: The AWS user or role must have permission to subscribe to the SNS topic.
bash
aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic --protocol email --notification-endpoint invalid-email # Correct usage: aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic --protocol email --notification-endpoint user@example.com
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| TopicArn | The Amazon Resource Name of the SNS topic | arn:aws:sns:us-east-1:123456789012:MyTopic |
| Protocol | The communication protocol (email, sms, http, https, lambda) | |
| Endpoint | The destination address or function for notifications | user@example.com |
| SubscriptionArn | The identifier returned after subscription (pending until confirmed) | pending confirmation |
Key Takeaways
Use the Subscribe API or AWS CLI with TopicArn, Protocol, and Endpoint to create a subscription.
Confirm the subscription via the endpoint to start receiving messages.
Ensure the endpoint format matches the protocol and permissions are set correctly.
Common protocols include email, sms, http, https, and lambda.
Subscription remains pending until confirmed by the subscriber.