Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

AWS CLI SNS Commands: Create Topic, Subscribe and Publish

We send one message to many receivers: create a topic, subscribe email and SQS, publish, filter and clean up.

In this chapter

  • Create a topic
  • Subscribe email and SQS
  • Publish messages
  • Use filter policies
  • Send SMS and clean up

1. The big picture: a WhatsApp group

You post once in a society WhatsApp group and every member gets it. SNS is that group: you publish once to a topic and every subscriber gets a copy.

Commands are in aws sns: create-topic, subscribe, publish, set-subscription-attributes, delete-topic.

Pub/sub workflowcreate-topicsubscribe email / sqs / lambdaconfirm the emailpublishevery subscriber gets a copy
Email subscriptions stay pending until confirmed.

2. Create a topic

Many systems need the same news, like "order placed".

A topic is a named channel with an ARN. Standard topics are fast; FIFO topics keep order.

  1. Create it.
T=$(aws sns create-topic --name cli-alerts --query TopicArn --output text)
echo $T

Expected output:

arn:aws:sns:ap-south-1:111122223333:cli-alerts
  1. List topics.
aws sns list-topics --query "Topics[].TopicArn" --output text

Expected output:

arn:aws:sns:ap-south-1:111122223333:cli-alerts

3. Subscribe

Think through a single publish before using the commands. The publisher sends to the topic ARN. Each subscription names a destination, such as your classroom inbox or an SQS queue. An email subscription must be confirmed by the recipient. A queue destination needs permission to accept delivery from the intended SNS topic.

With your lab topic, publish one tagged message and check the relevant subscriber. If you add a filter, send two messages whose filter fields differ. For a filter that selects priority=high, the high-priority message should arrive and the low-priority one should be left out after the setting takes effect. The returned message ID tells you the topic accepted the publish. It does not identify which subscriptions received the message.

People want email and programs want a queue.

subscribe takes a protocol (email, sqs, lambda, https, sms) and an endpoint. Email needs a click to confirm.

  1. Subscribe an email.
aws sns subscribe --topic-arn $T --protocol email --notification-endpoint you@example.com

Expected output:

{"SubscriptionArn": "pending confirmation"}
  1. Subscribe an SQS queue.
Q=arn:aws:sqs:ap-south-1:111122223333:cli-q
aws sns subscribe --topic-arn $T --protocol sqs --notification-endpoint $Q --attributes RawMessageDelivery=true --query SubscriptionArn --output text

Expected output:

arn:aws:sns:ap-south-1:111122223333:cli-alerts:5e6f...
  1. List subscriptions.
aws sns list-subscriptions-by-topic --topic-arn $T --query "Subscriptions[].[Protocol,SubscriptionArn]" --output text

Expected output:

email  PendingConfirmation
sqs    arn:aws:sns:...:5e6f...

4. Publish

Your app must announce an event once without knowing who listens.

publish sends a message with an optional subject and message attributes. It returns a MessageId.

  1. Publish a message.
aws sns publish --topic-arn $T --subject "Order" --message "Order 101 placed" --message-attributes '{"type":{"DataType":"String","StringValue":"order"}}' --query MessageId --output text

Expected output:

b7c8d9e0-1234-5678-9abc-def012345678
  1. Send one SMS.
aws sns publish --phone-number +919800000000 --message "OTP 4321" --query MessageId --output text

Expected output:

f1e2d3c4-...

5. Filter policies

Start by locating the subscription ARN, which identifies which destination will receive the policy. The topic ARN identifies the channel and is what you publish to. With the filter set on one subscription, an unfiltered subscription on the same topic may still receive both events. This makes it useful to keep one approved lab subscriber for comparison.

Work through the synthetic example before running the commands. One publish has the expected priority field, and one carries a different value. Record both message IDs. The matching subscription should receive the first after the filter is active; the comparison subscription can receive both. If no message arrives, confirm the exact topic and endpoint before investigating the policy. If both arrive where one was expected, inspect the policy scope and allow time for its update to take effect.

The billing queue wants only payment events, not every message.

A FilterPolicy on a subscription lets through only messages whose attributes match.

  1. Set a filter.
S=$(aws sns list-subscriptions-by-topic --topic-arn $T --query "Subscriptions[?Protocol=='sqs'].SubscriptionArn" --output text)
aws sns set-subscription-attributes --subscription-arn $S --attribute-name FilterPolicy --attribute-value '{"type":["payment"]}'

Expected output:

(no output means success)
  1. Verify.
aws sns get-subscription-attributes --subscription-arn $S --query Attributes.FilterPolicy --output text

Expected output:

{"type":["payment"]}

6. Same action in Python, Node.js, Java, Go, .NET and PHP

Scripts start in the CLI. Apps call the same API through an SDK. Knowing both helps you move a tested command into real code.

Low-level CLI commands expose service operations. A high-level command or an automatically paginated list can make multiple requests. For example, aws sns publish --topic-arn $T --message "hi" maps to the Publish API.

Same action (Publish) from code. Set the intended profile and Region for the SDK. Provider support and precedence can differ by SDK, and an explicit client setting can override defaults.

StackCode
Python (boto3)boto3.client("sns").publish(TopicArn=T,Message="hi")
Node.js (v3)await sns.send(new PublishCommand({TopicArn:T,Message:"hi"}));
Java (v2)sns.publish(r -> r.topicArn(t).message("hi"));
Go (v2)c.Publish(ctx, &sns.PublishInput{TopicArn: aws.String(t), Message: aws.String("hi")})
.NETawait sns.PublishAsync(new PublishRequest{TopicArn=t,Message="hi"});
PHP$sns->publish(["TopicArn"=>$t,"Message"=>"hi"]);

7. Clean up so nothing keeps costing

Lab resources left running cost money and can be a security risk.

Delete in reverse order: children first, then parents.

  1. Delete the topic (subscriptions go too).
aws sns delete-topic --topic-arn $T

Expected output:

(no output means success)
  1. Verify.
aws sns list-topics --query "Topics[?contains(TopicArn,'cli-alerts')]"

Expected output:

[]

Ravindra Bagale's Tip

For SNS to SQS, the queue policy must allow sns.amazonaws.com to SendMessage with your topic as the source, or messages silently never arrive.

Common errors: cause and safe next check

subscribe returns success, but the email never receives publish messages

Email subscriptions must be confirmed before the address can receive messages. The CLI example often shows SubscriptionArn as pending confirmation. Check the inbox for the Amazon SNS confirm link and confirm before you republish.

publish is sent to the topic name instead of the topic ARN

create-topic returns a TopicArn. Publish and subscribe need that ARN, not only the short name. Inspect the create-topic output and pass the ARN in later commands.

Someone adds personal details into the topic name

Official guidance says not to put personally identifiable or sensitive information in topic names, because names can appear in other AWS services. Use a short synthetic name and keep private data out of the name field.

Practical questions and full answers

What is the usual order of SNS CLI work?

Create a topic with create-topic, note the TopicArn, subscribe an endpoint with subscribe, confirm the subscription when the protocol requires it, then publish messages to the topic ARN. That order matches the beginner path in the SNS developer guide.

Why does an email subscribe show pending confirmation?

After you subscribe an email address, you must confirm the subscription from the email Amazon SNS sends before that address can start receiving messages. Until then, delivery to that email endpoint should not be expected.

Can I change a topic from standard to FIFO after creation?

During creation you choose the topic type and name. After creating a topic, you cannot change the topic type or name. If you need FIFO, create a new topic with the correct type and naming rules, then move subscribers carefully.

8. Interview questions and answers

Q. SNS vs SQS?

SNS pushes to many subscribers. SQS stores messages until one consumer pulls them.

Q. What is fan-out?

One SNS topic delivering to many SQS queues.

Q. Why pending confirmation?

Email endpoints must confirm to prevent spam.

Q. What does a filter policy do?

Drops messages whose attributes do not match for that subscription.

Q. What is RawMessageDelivery?

Sends only the message body, without the SNS JSON wrapper.

Try at home

  1. Fan out one topic to two queues and publish once.
  2. Add a filter so one queue gets only type=payment.

In short

  1. create-topic.
  2. subscribe protocol + endpoint.
  3. Confirm email.
  4. publish once.
  5. FilterPolicy.

Confirm a subscription before testing a publish

Create a dedicated topic and one email subscription. Confirm it from the receiving inbox, then publish one harmless message. A returned MessageId identifies the publish call; verify subscriber delivery separately.

Interview check Is a successful publish a guarantee of email receipt?

No. The topic accepted the message, but a subscription must be confirmed and delivery can fail downstream.

Reference documentation

Practise this chapter

Interview questions and answers

How would you diagnose one SNS subscription that gets no messages?

I would confirm the topic accepts a synthetic publish, then inspect that subscription’s confirmation, destination permissions and filter scope. I would send a matching and a nonmatching event and check the intended endpoint. The publisher cannot tell all of that from its message ID.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What proves that one email subscription is usable for a topic?

Answer and explanation

C. The recipient confirmed the intended subscription

A pending email subscription has not yet been confirmed by its recipient.

2. How do you check that a priority filter affects delivery?

Answer and explanation

B. Send matching and nonmatching messages to the same topic

Comparing two controlled cases tests which messages actually arrive at the subscriber.

3. A Publish call returns a message ID. What does it establish?

Answer and explanation

B. SNS accepted the publish request

Individual subscription delivery and processing are separate from the initial accepted publish.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Stockholm Games is a gaming business in Stockholm. Erik Lindqvist looks after its IT and cloud work. They count money in SEK and run their AWS resources in the eu-north-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 11

Easy Publish to one topic

An alerting app only needs to publish.

Allow sns:Publish on arn:aws:sns:eu-north-1:124495484726:sthlmgames-alerts only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Easy Publish a message

One publish reaches email, SMS, SQS and Lambda subscribers together.

Publish the message "Stock low in Stockholm" with subject "Stock alert" to arn:aws:sns:eu-north-1:124495484726:sthlmgames-alerts.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Create an SNS topic

A topic is a channel: publish once, every subscriber gets it.

Create topic sthlmgames-alerts.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Create a queue

A queue holds work safely until a worker is ready.

Create queue sthlmgames-orders.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Send an SMS directly

SNS can send a one-off SMS to a phone number without a topic.

Send the SMS "Your OTP is 482913" to +919800000001.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Producer may only send

The web app should add jobs but never read or delete them.

Allow sqs:SendMessage on arn:aws:sqs:eu-north-1:124495484726:sthlmgames-orders only.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Subscribe an email

Email subscribers must click the confirm link before they receive messages.

Subscribe ops@sthlmgames.se by email to arn:aws:sns:eu-north-1:124495484726:sthlmgames-alerts.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Delete a processed message

If you do not delete it, the message comes back after the visibility timeout.

Delete the message with receipt handle stored in $RH from https://sqs.eu-north-1.amazonaws.com/124495484726/sthlmgames-orders.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Add a subscription filter policy

A filter policy sends a subscriber only the messages it cares about.

Set the FilterPolicy of subscription arn:aws:sns:eu-north-1:124495484726:sthlmgames-alerts:4b1c-77 to {"type":["refund"]}.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Subscribe a queue to a topic

Fan-out: one SNS message is copied to many SQS queues for different workers.

Subscribe queue arn:aws:sqs:eu-north-1:124495484726:sthlmgames-billing to arn:aws:sns:eu-north-1:124495484726:sthlmgames-alerts.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Attach a dead-letter queue

After a few failed tries, bad messages move to a DLQ instead of blocking the queue.

Set the attributes in attrs.json (a RedrivePolicy) on https://sqs.eu-north-1.amazonaws.com/124495484726/sthlmgames-orders.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

SNS publish. Post once, everyone in the group gets it. create-topic, then subscribe endpoints. Email stays pending until clicked. publish returns a MessageId.
Revision card: SNS publish · Download PNG · Open card page
SNS filter policy. Billing wants only payment events. Publish with message attributes. Set FilterPolicy on the subscription. Non-matching messages are skipped.
Revision card: SNS filter policy · Download PNG · Open card page
SNS vs SQS. Push to many subscribers. / Pull by one consumer.
Comparison: SNS vs SQS · Download PNG · Open card page
SNS to SQS not arriving?. Queue policy must allow sns.amazonaws.com. Condition aws:SourceArn = topic ARN. Check FilterPolicy is not dropping it.
Interview card: SNS to SQS not arriving? · Download PNG · Open card page

More cards: Ravi Sir's Cards.