搭配 AWS CLI 使用 Amazon SNS - AWS Command Line Interface

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

搭配 AWS CLI 使用 Amazon SNS

您可以使用 AWS Command Line Interface (AWS CLI) 存取 Amazon Simple Notification Service (Amazon SNS) 的功能。若要列出 Amazon SNS 的 AWS CLI 命令,請使用下列命令。

aws sns help

在執行任何命令前,請先設定您的預設憑證。如需詳細資訊,請參閱 配置 AWS CLI

本主題顯示執行 Amazon SNS 常見任務的 AWS CLI 命令範例。

建立主題

若要建立主題,請使用 sns create-topic 命令,並指定要指派給主題的名稱。

$ aws sns create-topic --name my-topic { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" }

記下回應的 TopicArn,稍後您將使用它來發佈訊息。

訂閱主題

若要訂閱主題,請使用 sns subscribe 命令。

以下範例指定 email 通訊協定和 notification-endpoint 的電子郵件地址。

$ aws sns subscribe --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --protocol email --notification-endpoint saanvi@example.com { "SubscriptionArn": "pending confirmation" }

AWS 會立即透過電子郵件傳送確認信到您在 subscribe 命令中所指定的地址。電子郵件訊息會有以下文字。

You have chosen to subscribe to the topic: arn:aws:sns:us-west-2:123456789012:my-topic To confirm this subscription, click or visit the following link (If this was in error no action is necessary): Confirm subscription

收件人按一下 Confirm subscription (確認訂閱) 連結之後,收件人的瀏覽器會顯示一個通知訊息,其中包含以下資訊。

Subscription confirmed! You have subscribed saanvi@example.com to the topic:my-topic. Your subscription's id is: arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE If it was not your intention to subscribe, click here to unsubscribe.

發布到主題

若要將訊息傳送給一個主題的所有訂閱者,請使用 sns publish 命令。

以下範例會傳送「Hello World!」訊息 給指定主題的所有訂閱者。

$ aws sns publish --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --message "Hello World!" { "MessageId": "4e41661d-5eec-5ddf-8dab-2c867EXAMPLE" }

在這個範例中,AWS 會傳送一封電子郵件訊息 (其中包含文字「Hello World!」) 至 saanvi@example.com

取消訂閱主題

若要取消訂閱主題並停止接收發佈給該主題的訊息,請使用 sns unsubscribe 命令並指定您想要取消訂閱的主題 ARN。

$ aws sns unsubscribe --subscription-arn arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE

若要驗證是否成功取消訂閱,請使用 sns list-subscriptions 命令來確認 ARN 不再顯示於清單中。

$ aws sns list-subscriptions

刪除主題

若要刪除主題,請使用 sns delete-topic 命令。

$ aws sns delete-topic --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic

若要驗證 AWS 是否成功刪除主題,請使用 sns list-topics 命令來確認主題不再顯示於清單中。

$ aws sns list-topics