Hong  Nhung

Hong Nhung

1658000340

Các Lệnh AWS SNS CLI Với Các Ví Dụ

SNS là một dịch vụ được sử dụng để gửi tin nhắn đến nhiều người tiêu dùng (thuê bao). Để quản lý SNS AWS CLI được sử dụng. Trong hướng dẫn này, tôi sẽ đưa ra các ví dụ về cách quản lý dịch vụ SNS bằng AWS CLI mà không cần tạo SNS thực trên đám mây.

Hướng dẫn này dựa trên tài liệu chính thức của AWS CLI . Tôi sẽ chỉ trình bày các ví dụ về các lệnh có thể được thực thi cục bộ vì một số lệnh trong số đó chỉ có thể được sử dụng với các tài nguyên được tạo trên đám mây. Vì hướng dẫn này là một hướng dẫn thực tế, tôi thực sự khuyên bạn nên tham khảo tài liệu chính thức để biết thông tin đầy đủ về các lệnh, các tham số bắt buộc và tùy chọn, kết quả đầu ra, v.v.

Để quản lý các dịch vụ AWS, AWS CLI được sử dụng, hãy đảm bảo rằng bạn đã cài đặt AWS trên PC của mình. Phiên bản CLI trên PC của tôi là 2.7.14. Để đơn giản hơn, tôi sẽ sử dụng Localstack chạy trên Docker container bằng Docker Compose để tạo tài nguyên cục bộ cần thiết. Dưới đây là tệp docker-compos.yaml với định nghĩa vùng chứa Localstack:

version: '3.9'
services:
  localstack:
    container_name: localstack
    image: localstack/localstack:0.14.4
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=sns,sqs

Như bạn có thể thấy một biến môi trường chứa các dịch vụ cần thiết được chuyển đến vùng chứa. Tất nhiên, chúng ta cần phải có SNS. Bạn có thể tự hỏi mình, tại sao chúng ta cần SQS. Bởi vì sau này, chúng tôi sẽ cần một hàng đợi để phục vụ như một người đăng ký một chủ đề SNS.

Để tạo vùng chứa Docker với Localstack từ thư mục chứa tệp này, hãy thực hiện lệnh Docker Compose sau:

$docker-compose up

Trong vòng chưa đầy một phút, vùng chứa sẽ sẵn sàng chấp nhận các lệnh.

Tạo một chủ đề:

Lệnh tạo chủ đề:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic\
 --attributes DisplayName=tutorial-topic,\
DeliveryPolicy="\"{\\\"http\\\":{\\\"defaultHealthyRetryPolicy\\\":{\\\"minDelayTarget\\\":20,\\\"maxDelayTarget\\\":20,\\\"numRetries\\\":3,\\\"numMaxDelayRetries\\\":0,\\\"numNoDelayRetries\\\":0,\\\"numMinDelayRetries\\\":0,\\\"backoffFunction\\\":\\\"linear\\\"},\\\"disableSubscriptionOverrides\\\":false}}\""

JSON có thể được sử dụng để chuyển các thuộc tính khi tạo chủ đề:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json\
 --attributes '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}'

Các thuộc tính có thể được lưu trong tệp JSON và sau đó tệp này có thể được tham chiếu từ lệnh. Đầu tiên, chúng ta phải tạo một tệp bằng cách thực hiện lệnh:

$echo '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}' > create-sns-topic-attributes.json

Sau khi tệp được tạo, chúng ta phải tham chiếu đến nó trong lệnh:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json-file\
 --attributes file://create-sns-topic-attributes.json

Liệt kê các chủ đề:

Để liệt kê tất cả các chủ đề, lệnh dưới đây được sử dụng. Lọc đầu ra và phân trang có thể đạt được bằng cách cung cấp lệnh với các đối số tùy chọn:

$aws --endpoint-url=http://localhost:4566\
 sns  list-topics\
 --starting-token=0\
 --max-items=3

Nhận thuộc tính chủ đề:

$aws --endpoint-url=http://localhost:4566\
 sns get-topic-attributes \
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"

Đặt thuộc tính chủ đề:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DisplayName \
 --attribute-value new-tutorial-topic-name

Một vi dụ khac:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DeliveryPolicy\
 --attribute-value "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":10,\"maxDelayTarget\":10,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"

SNS chỉ chấp nhận một thuộc tính cho mỗi lệnh, vì vậy bạn có thể đặt 2 thuộc tính trong cùng một lần chạy và thuộc tính thứ hai sẽ chiếm ưu thế.

Đăng ký một chủ đề:

Để đăng ký một chủ đề, chúng tôi phải có một người đăng ký. Cách dễ nhất để tạo một thuê bao SNS cục bộ là tạo SQS:

$aws --endpoint-url=http://localhost:4566\
 sqs create-queue\
 --queue-name=tutorial-queue

Sau đó, chúng tôi tham chiếu đến hàng đợi này trong lệnh đăng ký:

$aws --endpoint-url=http://localhost:4566 \
 sns subscribe \
--topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic" \
--protocol=sqs \
--notification-endpoint=http://localhost:4566/000000000000/tutorial-queue \
--return-subscription-arn 

Vì vậy, bây giờ tất cả các tin nhắn được xuất bản cho một chủ đề sẽ được gửi đến người đăng ký mà trong trường hợp của chúng tôi là một SQS. Đối với tất cả các loại thuê bao, vui lòng tham khảo tài liệu.

Liệt kê các đăng ký:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions\
 --starting-token=0\
 --max-items=3

Liệt kê các đăng ký theo chủ đề:

Chúng tôi có thể kiểm tra người đăng ký cho một chủ đề cụ thể:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions-by-topic\
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --starting-token=0\
 --max-items=3

Đặt thuộc tính đăng ký:

$aws --endpoint-url=http://localhost:4566\
 sns set-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1\
 --attribute-name=RawMessageDelivery\
 --attribute-value=true

Nhận các thuộc tính đăng ký:

$aws --endpoint-url=http://localhost:4566\
 sns get-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1

Xuất bản một tin nhắn:

Chúng tôi có thể xuất bản tin nhắn theo nhiều cách khác nhau. Đầu tiên là sử dụng lệnh truyền thống và gửi nó dưới dạng một chuỗi đơn giản:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message="Tutorial topic message"\
 --subject="subject"\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Thực hiện lệnh trên và một lệnh nữa để kiểm tra xem thuê bao có nhận được tin nhắn hay không:

Hoặc chúng tôi có thể gửi nó dưới dạng JSON. Trong trường hợp này, chúng ta phải chỉ định cấu trúc thông báo và nhúng thông báo vào bên trong đối tượng JSON cấp cao nhất có tên “mặc định”:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message='{"default": "{\"message\": \"JSON tutorial topic message!\"}"}'\
 --subject="subject"\
 --message-structure=json\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Chúng ta có thể lưu một tin nhắn và các thuộc tính của nó trong các tệp riêng biệt và sau đó tham chiếu đến các tệp đó trong lệnh.

Lệnh tạo tệp với thông báo:

$echo '{"message": "Tutorial topic message (form file)"}' > sns-message.json

Lệnh tạo tệp với các thuộc tính của thông báo trên:

$echo '{
     "attribute1Value": {
          "DataType": "String",
          "StringValue": "attribute1Value"
     },
     "attribute2Value": {
          "DataType": "String",
          "StringValue": "attribute2Value"
     }
}' > sns-message-attributes.json

Lệnh xuất bản thông báo tham chiếu đến các tệp đã tạo trước đó:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message=file://sns-message.json \
 --subject="subject"\
 --message-attributes=file://sns-message-attributes.json

Xuất bản một tin nhắn trong một loạt:

Chúng tôi có thể xuất bản nhiều thư trong lô bằng cách sử dụng lệnh dưới đây:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries='[{
     "Id": "Batch-1",
     "Subject": "Subject-Batch-1",
     "Message": "{\"message\": \"Tutorial topic message batch-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-2",
     "Subject": "Subject-Batch-2",
     "Message": "{\"message\": \"Tutorial topic message from batch-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]'

Và sau đó kiểm tra xem các tin nhắn đã đến người đăng ký chưa:

Chúng tôi có thể xuất bản nhiều thông báo trong lô từ tệp. Đầu tiên, chúng tôi tạo một tệp:

$echo '[{
     "Id": "Batch-From-File-1",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-From-File-2",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]' > sns-message-in-batch.json

Sau đó, sử dụng nó trong lệnh:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries=file://sns-message-in-batch.json

Hủy đăng ký một chủ đề:

Để hủy đăng ký một chủ đề, lệnh được sử dụng:

$aws --endpoint-url=http://localhost:4566\
 sns unsubscribe\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:dcdf90f9-4a48-44b0-a3f4-fb51ec1827e4

Sử dụng lệnh này cục bộ không hoạt động như mong đợi, sau khi chạy lệnh này nhiều lần đăng ký không bị xóa… Đồng thời, chạy lệnh này với SNS trên đám mây hoạt động hoàn hảo. Đây có thể là một số lỗi. Nếu bạn biết tại sao nó không hoạt động, hãy cho tôi biết trong phần bình luận bên dưới.

Xóa chủ đề:

$aws --endpoint-url=http://localhost:4566\
 sns delete-topic \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic

Như tôi đã viết ở phần đầu, tất cả các lệnh hiển thị ở đây sẽ hoạt động với các hàng đợi trong đám mây. Khi sử dụng các lệnh đó với các chủ đề được lưu trữ trên đám mây, bạn sẽ không cần chỉ định:

--endpoint-url=http://localhost:4566

Vì nó được sử dụng để trỏ lệnh tới Localstack đang chạy trong vùng chứa Docker cục bộ. Theo mặc định, không có đối số trên, CLI sẽ gửi lệnh đến đám mây. Bạn có thể cần thêm tùy chọn bên dưới cho lệnh nếu bạn cần chỉ định một cấu hình khác (thông tin xác thực) để truy cập đám mây miễn là bạn có cấu hình được tạo trong tệp thông tin xác thực nằm trong thư mục .aws .

--profile=<profile-name>

Nếu không chỉ định đối số này, CLI sẽ sử dụng một hồ sơ mặc định (thông tin xác thực).

Sự kết luận

Đây là hướng dẫn thực tế về cách quản lý AWS SNS bằng AWS CLI. Tôi đã trình bày hầu hết các lệnh nhưng không phải tất cả vì một số lệnh không thể được thực hiện cục bộ. Tuy nhiên, nó vẫn đủ để bao gồm hầu hết các trường hợp sử dụng. Cảm ơn bạn đã đọc! Hãy like và theo dõi. Nếu bạn có bất kỳ câu hỏi hoặc đề xuất nào, vui lòng viết thư cho tôi trên tài khoản LinkedIn của tôi .

Liên kết: https://medium.com/faun/aws-sns-cli-commands-with-examples-370653951cef

#aws #sns #cli

Các Lệnh AWS SNS CLI Với Các Ví Dụ
Thierry  Perret

Thierry Perret

1657985888

Commandes De L'interface De Ligne De Commande AWS SNS Avec Exemples

Le SNS est un service utilisé pour envoyer des messages à plusieurs consommateurs (abonnés). Pour gérer les SNS, AWS CLI est utilisé. Dans ce didacticiel, je montrerai des exemples de gestion du service SNS à l'aide de l'AWS CLI sans avoir besoin de créer un véritable SNS sur le cloud.

Ce didacticiel est basé sur la documentation officielle de l'AWS CLI . Je ne montrerai que des exemples de commandes pouvant être exécutées localement puisque certaines d'entre elles ne peuvent être utilisées qu'avec les ressources créées sur le cloud. Comme ce tutoriel est un guide pratique, je vous recommande fortement de vous référer à la documentation officielle pour des informations complètes sur les commandes, leurs paramètres obligatoires et facultatifs, les sorties, etc.

Pour gérer les services AWS, l' AWS CLI est utilisée, assurez-vous qu'elle est installée sur votre PC. La version de CLI sur mon PC est 2.7.14. Pour plus de simplicité, j'utiliserai un Localstack exécuté sur un conteneur Docker à l'aide de Docker Compose pour créer les ressources nécessaires localement. Le fichier docker-compose.yaml avec une définition de conteneur Localstack est ci-dessous :

version: '3.9'
services:
  localstack:
    container_name: localstack
    image: localstack/localstack:0.14.4
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=sns,sqs

Comme vous pouvez le voir, une variable d'environnement contient les services nécessaires transmis au conteneur. Bien sûr, nous devons avoir un SNS. Vous vous demandez peut-être pourquoi avons-nous besoin de SQS. Parce que plus tard, nous aurons besoin d'une file d'attente pour servir d'abonné à un sujet SNS.

Pour créer un conteneur Docker avec Localstack à partir du répertoire où se trouve ce fichier, exécutez la commande Docker Compose suivante :

$docker-compose up

En moins d'une minute, le conteneur sera prêt à accepter des commandes.

Créer un sujet :

La commande pour créer un sujet :

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic\
 --attributes DisplayName=tutorial-topic,\
DeliveryPolicy="\"{\\\"http\\\":{\\\"defaultHealthyRetryPolicy\\\":{\\\"minDelayTarget\\\":20,\\\"maxDelayTarget\\\":20,\\\"numRetries\\\":3,\\\"numMaxDelayRetries\\\":0,\\\"numNoDelayRetries\\\":0,\\\"numMinDelayRetries\\\":0,\\\"backoffFunction\\\":\\\"linear\\\"},\\\"disableSubscriptionOverrides\\\":false}}\""

Le JSON peut être utilisé pour transmettre des attributs lors de la création d'un sujet :

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json\
 --attributes '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}'

Les attributs peuvent être enregistrés dans le fichier JSON, puis ce fichier peut être référencé à partir de la commande. Premièrement, nous devons créer un fichier en exécutant la commande :

$echo '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}' > create-sns-topic-attributes.json

Une fois le fichier créé, nous devons nous y référer dans la commande :

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json-file\
 --attributes file://create-sns-topic-attributes.json

Lister les sujets :

Pour lister tous les sujets, la commande ci-dessous est utilisée. Le filtrage et la pagination de la sortie peuvent être obtenus en fournissant à la commande des arguments facultatifs :

$aws --endpoint-url=http://localhost:4566\
 sns  list-topics\
 --starting-token=0\
 --max-items=3

Obtenir les attributs du sujet :

$aws --endpoint-url=http://localhost:4566\
 sns get-topic-attributes \
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"

Définissez les attributs du sujet :

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DisplayName \
 --attribute-value new-tutorial-topic-name

Un autre exemple:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DeliveryPolicy\
 --attribute-value "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":10,\"maxDelayTarget\":10,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"

SNS accepte un seul attribut par commande, vous pouvez donc définir 2 attributs dans la même exécution, et le deuxième attribut prévaudra.

Abonnez-vous à un sujet :

Pour s'abonner à un sujet, nous devons avoir un abonné. Le moyen le plus simple de créer un abonné SNS localement est de créer SQS :

$aws --endpoint-url=http://localhost:4566\
 sqs create-queue\
 --queue-name=tutorial-queue

Ensuite, nous nous référons à cette file d'attente dans la commande subscribe :

$aws --endpoint-url=http://localhost:4566 \
 sns subscribe \
--topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic" \
--protocol=sqs \
--notification-endpoint=http://localhost:4566/000000000000/tutorial-queue \
--return-subscription-arn 

Alors maintenant, tous les messages publiés sur un sujet seront envoyés à l'abonné qui, dans notre cas, est un SQS. Pour tous les types d'abonnés, veuillez vous référer à la documentation.

Liste des abonnements :

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions\
 --starting-token=0\
 --max-items=3

Répertorier les abonnements par thème :

Nous pouvons vérifier les abonnés pour un sujet spécifique :

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions-by-topic\
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --starting-token=0\
 --max-items=3

Définissez les attributs d'abonnement :

$aws --endpoint-url=http://localhost:4566\
 sns set-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1\
 --attribute-name=RawMessageDelivery\
 --attribute-value=true

Obtenir les attributs d'abonnement :

$aws --endpoint-url=http://localhost:4566\
 sns get-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1

Publier un message :

Nous pouvons publier des messages de différentes manières. La première consiste à utiliser la commande traditionnelle et à l'envoyer sous forme de chaîne :

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message="Tutorial topic message"\
 --subject="subject"\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Exécutez la commande ci-dessus et une autre commande pour vérifier si l'abonné a reçu le message :

Ou nous pouvons l'envoyer en tant que JSON. Dans ce cas, nous devons spécifier la structure du message et incorporer le message dans l'objet JSON de niveau supérieur nommé "default":

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message='{"default": "{\"message\": \"JSON tutorial topic message!\"}"}'\
 --subject="subject"\
 --message-structure=json\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Nous pouvons enregistrer un message et ses attributs dans des fichiers séparés, puis faire référence à ces fichiers dans la commande.

La commande pour créer un fichier avec un message :

$echo '{"message": "Tutorial topic message (form file)"}' > sns-message.json

La commande pour créer un fichier avec les attributs du message ci-dessus :

$echo '{
     "attribute1Value": {
          "DataType": "String",
          "StringValue": "attribute1Value"
     },
     "attribute2Value": {
          "DataType": "String",
          "StringValue": "attribute2Value"
     }
}' > sns-message-attributes.json

La commande de message de publication faisant référence aux fichiers créés précédemment :

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message=file://sns-message.json \
 --subject="subject"\
 --message-attributes=file://sns-message-attributes.json

Publiez un message dans un lot :

Nous pouvons publier plusieurs messages dans le lot à l'aide de la commande ci-dessous :

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries='[{
     "Id": "Batch-1",
     "Subject": "Subject-Batch-1",
     "Message": "{\"message\": \"Tutorial topic message batch-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-2",
     "Subject": "Subject-Batch-2",
     "Message": "{\"message\": \"Tutorial topic message from batch-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]'

Et puis vérifiez si les messages sont parvenus à l'abonné :

Nous pouvons publier plusieurs messages dans le lot à partir du fichier. Tout d'abord, nous créons un fichier :

$echo '[{
     "Id": "Batch-From-File-1",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-From-File-2",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]' > sns-message-in-batch.json

Puis en l'utilisant dans la commande :

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries=file://sns-message-in-batch.json

Se désinscrire d'un sujet :

Pour se désabonner d'un sujet, la commande est utilisée :

$aws --endpoint-url=http://localhost:4566\
 sns unsubscribe\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:dcdf90f9-4a48-44b0-a3f4-fb51ec1827e4

L'utilisation de cette commande localement ne fonctionne pas comme prévu, après avoir exécuté cette commande plusieurs fois, l'abonnement n'a pas été supprimé… En même temps, l'exécution de cette commande sur SNS dans le cloud a parfaitement fonctionné. Cela peut être un bug. Si vous savez pourquoi cela ne fonctionne pas, faites-le moi savoir dans la section commentaire ci-dessous.

Supprimer un sujet :

$aws --endpoint-url=http://localhost:4566\
 sns delete-topic \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic

Comme je l'ai écrit au début, toutes les commandes affichées ici fonctionneraient avec les files d'attente dans le cloud. Lorsque vous utilisez ces commandes avec des sujets hébergés dans le cloud, vous n'avez pas besoin de spécifier :

--endpoint-url=http://localhost:4566

Comme il est utilisé pour pointer la commande vers le Localstack exécuté localement dans le conteneur Docker. Par défaut, sans l'argument ci-dessus, CLI enverra des commandes au cloud. Vous devrez peut-être ajouter l'option ci-dessous pour la commande si vous devez spécifier un profil différent (informations d'identification) pour accéder au cloud tant que vous disposez d'un profil créé dans le fichier d'informations d' identification situé dans le répertoire .aws .

--profile=<profile-name>

Sans spécifier cet argument, CLI utilisera un profil par défaut (informations d'identification).

Conclusion

Il s'agissait d'un guide pratique sur la gestion d'AWS SNS à l'aide de l'AWS CLI. J'ai couvert la plupart des commandes mais pas toutes car certaines d'entre elles ne peuvent pas être exécutées localement. Mais cela reste suffisant pour couvrir la plupart des cas d'utilisation. Merci pour la lecture! Veuillez aimer et suivre. Si vous avez des questions ou des suggestions, n'hésitez pas à m'écrire sur mon compte LinkedIn .

Lien : https://medium.com/faun/aws-sns-cli-commands-with-examples-370653951cef

#aws #sns #cli

Commandes De L'interface De Ligne De Commande AWS SNS Avec Exemples
高橋  陽子

高橋 陽子

1657971443

帶有示例的 AWS SNS CLI 命令

SNS 是一種用於向多個消費者(訂閱者)傳遞消息的服務。使用 AWS CLI 管理 SNS。在本教程中,我將展示如何使用 AWS CLI 管理 SNS 服務而不需要在雲上創建真正的 SNS 的示例。

本教程基於 AWS CLI 官方文檔。我將僅演示可以在本地執行的命令示例,因為其中一些命令只能與在雲上創建的資源一起使用。由於本教程是一本實用指南,我強烈建議您參考官方文檔以獲取有關命令、其必需和可選參數、輸出等的完整信息。

要使用AWS CLI管理 AWS 服務,請確保您已將其安裝在您的 PC 上。我的 PC 上的 CLI 版本是 2.7.14。為簡單起見,我將使用在Docker容器上運行的Localstack ,使用Docker Compose在本地創建所需的資源。帶有 Localstack 容器定義的 docker-compose.yaml 文件如下

version: '3.9'
services:
  localstack:
    container_name: localstack
    image: localstack/localstack:0.14.4
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=sns,sqs

如您所見,環境變量包含傳遞給容器的所需服務。當然,我們需要有一個 SNS。你可能會問自己,為什麼我們需要 SQS。因為稍後,我們將需要一個隊列來充當 SNS 主題的訂閱者。

要從該文件所在的目錄創建具有 Localstack 的 Docker 容器,請執行以下 Docker Compose 命令:

$docker-compose up

不到一分鐘,容器將準備好接受命令。

創建主題:

創建主題的命令:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic\
 --attributes DisplayName=tutorial-topic,\
DeliveryPolicy="\"{\\\"http\\\":{\\\"defaultHealthyRetryPolicy\\\":{\\\"minDelayTarget\\\":20,\\\"maxDelayTarget\\\":20,\\\"numRetries\\\":3,\\\"numMaxDelayRetries\\\":0,\\\"numNoDelayRetries\\\":0,\\\"numMinDelayRetries\\\":0,\\\"backoffFunction\\\":\\\"linear\\\"},\\\"disableSubscriptionOverrides\\\":false}}\""

JSON 可用於在創建主題時傳遞屬性:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json\
 --attributes '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}'

屬性可以保存在 JSON 文件中,然後可以從命令中引用該文件。首先,我們必須通過執行命令來創建一個文件:

$echo '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}' > create-sns-topic-attributes.json

創建文件後,我們必須在命令中引用它:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json-file\
 --attributes file://create-sns-topic-attributes.json

列出主題:

要列出所有主題,請使用以下命令。輸出過濾和分頁可以通過提供帶有可選參數的命令來實現:

$aws --endpoint-url=http://localhost:4566\
 sns  list-topics\
 --starting-token=0\
 --max-items=3

獲取主題屬性:

$aws --endpoint-url=http://localhost:4566\
 sns get-topic-attributes \
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"

設置主題屬性:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DisplayName \
 --attribute-value new-tutorial-topic-name

另一個例子:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DeliveryPolicy\
 --attribute-value "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":10,\"maxDelayTarget\":10,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"

SNS每個命令只接受一個屬性,所以你可以在同一次運行中設置2個屬性,以第二個屬性為準。

訂閱一個主題:

要訂閱一個主題,我們必須有一個訂閱者。在本地創建 SNS 訂閱者的最簡單方法是創建 SQS :

$aws --endpoint-url=http://localhost:4566\
 sqs create-queue\
 --queue-name=tutorial-queue

然後我們在 subscribe 命令中引用這個隊列:

$aws --endpoint-url=http://localhost:4566 \
 sns subscribe \
--topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic" \
--protocol=sqs \
--notification-endpoint=http://localhost:4566/000000000000/tutorial-queue \
--return-subscription-arn 

所以現在所有發佈到主題的消息都將發送給訂閱者,在我們的例子中是一個 SQS。對於所有訂閱者類型,請參閱文檔。

列出訂閱:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions\
 --starting-token=0\
 --max-items=3

按主題列出訂閱:

我們可以檢查特定主題的訂閱者:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions-by-topic\
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --starting-token=0\
 --max-items=3

設置訂閱屬性:

$aws --endpoint-url=http://localhost:4566\
 sns set-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1\
 --attribute-name=RawMessageDelivery\
 --attribute-value=true

獲取訂閱屬性:

$aws --endpoint-url=http://localhost:4566\
 sns get-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1

發布消息:

我們可以通過不同的方式發布消息。第一種是使用傳統命令並將其作為純字符串發送:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message="Tutorial topic message"\
 --subject="subject"\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

執行上面的命令和另外一個命令來檢查訂閱者是否收到了消息:

或者我們可以將其作為 JSON 發送。在這種情況下,我們必須指定消息結構並將消息嵌入到名為“default”的頂級 JSON 對像中:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message='{"default": "{\"message\": \"JSON tutorial topic message!\"}"}'\
 --subject="subject"\
 --message-structure=json\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

我們可以將消息及其屬性保存在單獨的文件中,然後在命令中引用這些文件。

創建帶有消息的文件的命令:

$echo '{"message": "Tutorial topic message (form file)"}' > sns-message.json

創建具有上述消息屬性的文件的命令:

$echo '{
     "attribute1Value": {
          "DataType": "String",
          "StringValue": "attribute1Value"
     },
     "attribute2Value": {
          "DataType": "String",
          "StringValue": "attribute2Value"
     }
}' > sns-message-attributes.json

引用先前創建的文件的發布消息命令:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message=file://sns-message.json \
 --subject="subject"\
 --message-attributes=file://sns-message-attributes.json

批量發布消息:

我們可以使用以下命令批量發布多條消息:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries='[{
     "Id": "Batch-1",
     "Subject": "Subject-Batch-1",
     "Message": "{\"message\": \"Tutorial topic message batch-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-2",
     "Subject": "Subject-Batch-2",
     "Message": "{\"message\": \"Tutorial topic message from batch-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]'

然後檢查消息是否到達訂閱者:

我們可以從文件中批量發布多條消息。首先,我們創建一個文件:

$echo '[{
     "Id": "Batch-From-File-1",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-From-File-2",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]' > sns-message-in-batch.json

然後在命令中使用它:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries=file://sns-message-in-batch.json

取消訂閱主題:

取消訂閱主題命令使用:

$aws --endpoint-url=http://localhost:4566\
 sns unsubscribe\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:dcdf90f9-4a48-44b0-a3f4-fb51ec1827e4

在本地使用此命令無法按預期工作,多次運行此命令後訂閱未刪除......同時在雲中針對 SNS 運行此命令效果很好。這可能是一些錯誤。如果您知道為什麼它不起作用,請在下面的評論部分告訴我。

刪除主題:

$aws --endpoint-url=http://localhost:4566\
 sns delete-topic \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic

正如我在開頭所寫的那樣,此處顯示的所有命令都可以與雲中的隊列一起使用。將這些命令與託管在雲中的主題一起使用時,您無需指定:

--endpoint-url=http://localhost:4566

因為它用於將命令指向本地運行在 Docker 容器中的 Localstack。默認情況下,如果沒有上述參數,CLI 將向雲端發送命令。如果您需要指定不同的配置文件(憑證)來訪問云,您可能需要為命令添加以下選項,只要您在位於.aws目錄的憑證文件中創建了配置文件。

--profile=<profile-name>

如果不指定此參數,CLI 將使用默認配置文件(憑據)。

結論

這是關於如何使用 AWS CLI 管理 AWS SNS 的實用指南。我已經介紹了大部分命令,但不是全部,因為其中一些命令無法在本地執行。但是,它仍然足以涵蓋大多數用例。感謝您的閱讀!請喜歡並關注。如果您有任何問題或建議,請隨時在我的 LinkedIn帳戶上寫信給我。

鏈接:https ://medium.com/faun/aws-sns-cli-commands-with-examples-370653951cef

#aws #sns #cli

帶有示例的 AWS SNS CLI 命令

Команды AWS SNS CLI с примерами

SNS — это служба, используемая для доставки сообщений нескольким потребителям (подписчикам). Для управления SNS используется AWS CLI. В этом руководстве я покажу примеры того, как управлять сервисом SNS с помощью интерфейса командной строки AWS без необходимости создавать настоящий SNS в облаке.

Это руководство основано на официальной документации AWS CLI . Я буду демонстрировать только примеры команд, которые можно выполнять локально, так как некоторые из них можно использовать только с ресурсами, созданными в облаке. Поскольку это руководство является практическим руководством, я настоятельно рекомендую вам обратиться к официальной документации для получения полной информации о командах, их обязательных и необязательных параметрах, выводах и т. д.

Для управления сервисами AWS используется интерфейс командной строки AWS, убедитесь, что он установлен на вашем ПК. Версия CLI на моем ПК — 2.7.14. Для простоты я буду использовать Localstack , работающий в контейнере Docker, с помощью Docker Compose для локального создания необходимых ресурсов. Файл docker-compose.yaml с определением контейнера Localstack приведен ниже:

version: '3.9'
services:
  localstack:
    container_name: localstack
    image: localstack/localstack:0.14.4
    ports:
      - "4566-4599:4566-4599"
    environment:
      - SERVICES=sns,sqs

Как видите, переменная окружения содержит необходимые службы, переданные в контейнер. Конечно, нам нужно иметь SNS. Вы можете спросить себя, зачем нам нужен SQS. Потому что позже нам понадобится очередь, чтобы служить подписчиком темы SNS.

Чтобы создать контейнер Docker с Localstack из каталога, в котором находится этот файл, выполните следующую команду Docker Compose:

$docker-compose up

Менее чем через минуту контейнер будет готов принимать команды.

Создайте тему:

Команда для создания темы:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic\
 --attributes DisplayName=tutorial-topic,\
DeliveryPolicy="\"{\\\"http\\\":{\\\"defaultHealthyRetryPolicy\\\":{\\\"minDelayTarget\\\":20,\\\"maxDelayTarget\\\":20,\\\"numRetries\\\":3,\\\"numMaxDelayRetries\\\":0,\\\"numNoDelayRetries\\\":0,\\\"numMinDelayRetries\\\":0,\\\"backoffFunction\\\":\\\"linear\\\"},\\\"disableSubscriptionOverrides\\\":false}}\""

JSON можно использовать для передачи атрибутов при создании темы:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json\
 --attributes '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}'

Атрибуты могут быть сохранены в файле JSON, а затем этот файл может быть передан из команды. Во-первых, мы должны создать файл, выполнив команду:

$echo '{
     "DisplayName": "tutorial-topic-attributes-as-json",
     "DeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"
}' > create-sns-topic-attributes.json

После создания файла мы должны обратиться к нему в команде:

$aws --endpoint-url=http://localhost:4566\
 sns create-topic \
 --name=tutorial-topic-attributes-as-json-file\
 --attributes file://create-sns-topic-attributes.json

Список тем:

Чтобы перечислить все темы, используется команда ниже. Фильтрация вывода и разбиение на страницы могут быть достигнуты путем предоставления команде необязательных аргументов:

$aws --endpoint-url=http://localhost:4566\
 sns  list-topics\
 --starting-token=0\
 --max-items=3

Получить атрибуты темы:

$aws --endpoint-url=http://localhost:4566\
 sns get-topic-attributes \
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"

Установить атрибуты темы:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DisplayName \
 --attribute-value new-tutorial-topic-name

Другой пример:

$aws --endpoint-url=http://localhost:4566\
 sns set-topic-attributes\
 --topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic"\
 --attribute-name DeliveryPolicy\
 --attribute-value "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":10,\"maxDelayTarget\":10,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}"

SNS принимает только один атрибут для каждой команды, поэтому вы можете установить 2 атрибута в одном запуске, и второй атрибут будет иметь преимущественную силу.

Подпишитесь на тему:

Чтобы подписаться на тему, у нас должен быть подписчик. Самый простой способ создать локального подписчика SNS — создать SQS:

$aws --endpoint-url=http://localhost:4566\
 sqs create-queue\
 --queue-name=tutorial-queue

Затем мы обращаемся к этой очереди в команде subscribe:

$aws --endpoint-url=http://localhost:4566 \
 sns subscribe \
--topic-arn="arn:aws:sns:us-east-1:000000000000:tutorial-topic" \
--protocol=sqs \
--notification-endpoint=http://localhost:4566/000000000000/tutorial-queue \
--return-subscription-arn 

Итак, теперь все сообщения, опубликованные в теме, будут отправляться подписчику, которым в нашем случае является SQS. Для всех типов подписчиков см. документацию.

Список подписок:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions\
 --starting-token=0\
 --max-items=3

Список подписок по темам:

Мы можем проверить подписчиков по определенной теме:

$aws --endpoint-url=http://localhost:4566\
 sns list-subscriptions-by-topic\
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --starting-token=0\
 --max-items=3

Установите атрибуты подписки:

$aws --endpoint-url=http://localhost:4566\
 sns set-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1\
 --attribute-name=RawMessageDelivery\
 --attribute-value=true

Получить атрибуты подписки:

$aws --endpoint-url=http://localhost:4566\
 sns get-subscription-attributes\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:efd1257d-20ee-40e5-8e83-45bdac9b72f1

Опубликовать сообщение:

Мы можем публиковать сообщения по-разному. Первый использует традиционную команду и отправляет ее в виде простой строки:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message="Tutorial topic message"\
 --subject="subject"\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Выполните команду выше и еще одну команду, чтобы проверить, получил ли подписчик сообщение:

Или мы можем отправить его в формате JSON. В этом случае мы должны указать структуру сообщения и встроить сообщение в объект JSON верхнего уровня с именем «по умолчанию»:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message='{"default": "{\"message\": \"JSON tutorial topic message!\"}"}'\
 --subject="subject"\
 --message-structure=json\
 --message-attributes 'attribute1={DataType=String, StringValue="attribute1Value"},attribute2={DataType=String, StringValue="attribute2Value"}'

Мы можем сохранить сообщение и его атрибуты в отдельных файлах, а затем ссылаться на эти файлы в команде.

Команда для создания файла с сообщением:

$echo '{"message": "Tutorial topic message (form file)"}' > sns-message.json

Команда для создания файла с атрибутами вышеуказанного сообщения:

$echo '{
     "attribute1Value": {
          "DataType": "String",
          "StringValue": "attribute1Value"
     },
     "attribute2Value": {
          "DataType": "String",
          "StringValue": "attribute2Value"
     }
}' > sns-message-attributes.json

Команда публикации сообщения со ссылкой на ранее созданные файлы:

$aws --endpoint-url=http://localhost:4566\
 sns publish \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic\
 --message=file://sns-message.json \
 --subject="subject"\
 --message-attributes=file://sns-message-attributes.json

Опубликовать сообщение в пакете:

Мы можем опубликовать несколько сообщений в пакете, используя следующую команду:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries='[{
     "Id": "Batch-1",
     "Subject": "Subject-Batch-1",
     "Message": "{\"message\": \"Tutorial topic message batch-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-2",
     "Subject": "Subject-Batch-2",
     "Message": "{\"message\": \"Tutorial topic message from batch-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]'

А затем проверить, дошли ли сообщения до подписчика:

Мы можем публиковать несколько сообщений в пакете из файла. Сначала создаем файл:

$echo '[{
     "Id": "Batch-From-File-1",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-1!\"}",
      "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch1"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
},
{
     "Id": "Batch-From-File-2",
     "Subject": "Subject-Batch-From-File-1",
     "Message": "{\"message\": \"Tutorial topic message Batch-From-File-2!\"}",
     "MessageAttributes": {
          "attribute1Value": {
               "DataType": "String",
               "StringValue": "attribute1ValueBatch2"
          },
          "attribute2Value": {
               "DataType": "String",
               "StringValue": "attribute2ValueBatch2"
          }
     }
}]' > sns-message-in-batch.json

Затем используя его в команде:

$aws --endpoint-url=http://localhost:4566\
 sns publish-batch \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic \
 --publish-batch-request-entries=file://sns-message-in-batch.json

Отписаться от темы:

Для отписки от темы используется команда:

$aws --endpoint-url=http://localhost:4566\
 sns unsubscribe\
 --subscription-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic:dcdf90f9-4a48-44b0-a3f4-fb51ec1827e4

Локальное использование этой команды не работает должным образом, после многократного запуска этой команды подписка не удалялась… В то же время запуск этой команды на SNS в облаке работал отлично. Это может быть какой-то баг. Если вы знаете, почему это не работает, дайте мне знать в разделе комментариев ниже.

Удалить тему:

$aws --endpoint-url=http://localhost:4566\
 sns delete-topic \
 --topic-arn=arn:aws:sns:us-east-1:000000000000:tutorial-topic

Как я писал в начале, все показанные здесь команды будут работать с очередями в облаке. При использовании этих команд с темами, размещенными в облаке, вам не нужно указывать:

--endpoint-url=http://localhost:4566

Поскольку он используется для указания команды на Localstack, работающий в контейнере Docker локально. По умолчанию без указанного выше аргумента CLI будет отправлять команды в облако. Вам может потребоваться добавить приведенный ниже параметр для команды, если вам нужно указать другой профиль (учетные данные) для доступа к облаку, если у вас есть профиль, созданный в файле учетных данных , расположенном в каталоге .aws .

--profile=<profile-name>

Без указания этого аргумента CLI будет использовать профиль по умолчанию (учетные данные).

Вывод

Это было практическое руководство по управлению AWS SNS с помощью AWS CLI. Я рассмотрел большинство команд, но не все, потому что некоторые из них нельзя выполнить локально. Но тем не менее, этого достаточно, чтобы охватить большинство вариантов использования. Спасибо за чтение! Пожалуйста, поставьте лайк и подпишитесь. Если у вас есть какие-либо вопросы или предложения, пожалуйста, напишите мне в моей учетной записи LinkedIn .

Ссылка: https://medium.com/faun/aws-sns-cli-commands-with-examples-370653951cef

#aws #sns #cli

Команды AWS SNS CLI с примерами
Hermann  Frami

Hermann Frami

1656971520

Serverless Tag Sns Topic

serverless-tag-sns-topic

Serverless plugin to tag SNS Topic  (referred to serverless-tag-sqs 🎉)

Installation

Install the plugin via Github.

npm install --save-dev github:inokappa/serverless-tag-sns-topic

Usage

In Serverless template:

custom:
  snsTopicTags:
      -
        Key: 'key1'
        Value: 'value1'
      -
        Key: 'key2'
        Value: 'value2'


plugins: 
  - serverless-tag-sns-topic

Author: inokappa
Source Code: https://github.com/inokappa/serverless-tag-sns-topic 
License: 

#serverless #tag #sns 

Serverless Tag Sns Topic
Hermann  Frami

Hermann Frami

1656057720

Serverless Offline SNS

serverless-offline-sns

A serverless plugin to listen to offline SNS and call lambda fns with events.

Prerequisites

This plugin provides an SNS server configured automatically without you specifying an endpoint.

If you'd rather use your own endpoint, e.g. from your AWS account or a localstack SNS server endpoint, you can put it in the custom config. See below for details.

Installation

Install the plugin

npm install serverless-offline-sns --save

Let serverless know about the plugin

plugins:
  - serverless-offline-sns

Note that ordering matters when used with serverless-offline and serverless-webpack. serverless-webpack must be specified at the start of the list of plugins.

Configure the plugin with your offline SNS endpoint, host to listen on, and a free port the plugin can use.

custom:
  serverless-offline-sns:
    port: 4002 # a free port for the sns server to run on
    debug: false
    # host: 0.0.0.0 # Optional, defaults to 127.0.0.1 if not provided to serverless-offline
    # sns-endpoint: http://127.0.0.1:4567 # Optional. Only if you want to use a custom SNS provider endpoint
    # sns-subscribe-endpoint: http://127.0.0.1:3000 # Optional. Only if you want to use a custom subscribe endpoint from SNS to send messages back to
    # accountId: 123456789012 # Optional
    # location: .build # Optional if the location of your handler.js is not in ./ (useful for typescript)

For example, if you would like to connect to AWS and have callbacks coming via ngrok, use:

serverless-offline-sns:
    sns-endpoint: sns.${self:provider.region}.amazonaws.com
    sns-subscribe-endpoint: <ngrok_url>
    remotePort: 80
    localPort: <ngrok_port>
    accountId: ${self:provider.accountId}

In normal operation, the plugin will use the same --host option as provided to serverless-offline. The host parameter as shown above overrides this setting.

If you are using the serverless-offline plugin serverless-offline-sns will start automatically. If you are not using this plugin you can run the following command instead:

serverless offline-sns start

Configure

Configure your function handlers with events as described in the Serverless SNS Documentation

Here's an example serverless.yml config which calls a function on an SNS notifcation. Note that the offline-sns plugin will automatically pick up this config, subscribe to the topic and call the handler on an SNS notification.

functions:
  pong:
    handler: handler.pong
    events:
      - sns: test-topic

Or you can use the exact ARN of the topic, in 2 ways:

functions:
  pong:
    handler: handler.pong
    events:
      - sns:
         arn: "arn:aws:sns:us-east-1:123456789012:test-topic" # 1st way
      - sns: "arn:aws:sns:us-east-1:123456789012:test-topic-two" # 2nd way

Here's a demo of some code that will trigger this handler:

var AWS = require("aws-sdk"); // must be npm installed to use
var sns = new AWS.SNS({
  endpoint: "http://127.0.0.1:4002",
  region: "us-east-1",
});
sns.publish({
  Message: "{content: \"hello!\"}",
  MessageStructure: "json",
  TopicArn: "arn:aws:sns:us-east-1:123456789012:test-topic",
}, () => {
  console.log("ping");
});

Note the region that offline-sns will listen on is what is configured in your serverless.yml provider.

Localstack docker configuration

In order to listen to localstack SNS event, if localstack is started with docker, you need the following:

custom:
  serverless-offline-sns:
    host: 0.0.0.0 # Enable plugin to listen on every local address
    sns-subscribe-endpoint: 192.168.1.225 #Host ip address
    sns-endpoint: http://localhost:4575 # Default localstack sns endpoint

What happens is that the container running localstack will execute a POST request to the plugin, but to reach outside the container, it needs to use the host ip address.

Hosted AWS SNS configuration

In order to listen to a hosted SNS on AWS, you need the following:

custom:
  serverless-offline-sns:
    localPort: ${env:LOCAL_PORT}
    remotePort: ${env:SNS_SUBSCRIBE_REMOTE_PORT}
    host: 0.0.0.0
    sns-subscribe-endpoint: ${env:SNS_SUBSCRIBE_ENDPOINT}
    sns-endpoint: ${env:SNS_ENDPOINT}```

If you want to unsubscribe when you stop your server, then call sls offline-sns cleanup when the script exits.

Multiple serverless services configuration

If you have multiple serverless services, please specify a root directory:

custom:
  serverless-offline-sns:
    servicesDirectory: "/path/to/directory"

The root directory must contain directories with serverless.yaml files inside.

Usage

If you use serverless-offline this plugin will start automatically.

However if you don't use serverless-offline you can start this plugin manually with -

serverless offline-sns start

Subscribing

serverless-offline-sns supports http, https, and sqs subscriptions. email, email-json, sms, application, and lambda protocols are not supported at this time.

When using sqs the Endpoint for the subscription must be the full QueueUrl returned from the SQS service when creating the queue or listing with ListQueues:

// async
const queue = await sqs.createQueue({ QueueName: 'my-queue' }).promise();
const subscription = await sns.subscribe({
    TopicArn: myTopicArn,
    Protocol: 'sqs',
    Endpoint: queue.QueueUrl,
}).promise();

For an example of a working application please see serverless-offline-sns-example

Author: mj1618
Source Code: https://github.com/mj1618/serverless-offline-sns 
License: MIT license

#serverless #lambda #sns 

Serverless Offline SNS

サーバー「Server」とは?

サーバーについて解説している動画です!
聞いたことはあるけど、サーバーってどんなものなの?という方、必見の動画です!

サーバーとは、英語で書くと「Server」となり、提供する側という意味を持つ言葉です。利用者の要求(リクエスト)に対して、それに応答したデータを提供するコンピュータやプログラムのことを“サーバー”と呼んでいます。

サーバーの役割をもう少し簡単にイメージできるように、身近な例で見てみましょう。例えば、インターネットでWebサイトを見るときを想像してみてください。

特定のWebサイトを見る際は、まずWebブラウザにURLを入力し、Enterキーで決定します。このとき私たち(クライアント)は、Web上の住所(IPアドレス)を管理しているサーバーに、表示させたいWebサイトの住所を問い合わせ、表示をリクエストしているということになります。

Webサイトのページのデータを保管しているサーバーは、リクエストのあったWebサイトの画像やHTMLファイルといったデータを提供します。この一連の流れの結果、該当するURLのWebサイトが表示されるのです。

サーバーについて、少しはイメージしやすくなったでしょうか?
サーバーは、Webサイトの表示のほかにも、動画サイトやSNSへの投稿やメールの送受信など、普段私たちが何気なく行なっているさまざまなことに深く関係しているのです。

■目次
0:45 サーバーとは?
1:45 サーバーの種類 
5:08 サーバーの主な役割 用途
9:25 まとめ 
 

#sns #web 

サーバー「Server」とは?

SNS And SQS Deep Dive | Standard Vs FIFO and Use Cases

In this video, we are going to deep dive into following:

  1. What is SNS and SQS
  2. Difference between SNS and SQS
  3. How does SQS process messages under the hood
  4. Use cases of SQS and SNSs
  5. Tips and Best practices

#sns #sqs

SNS And SQS Deep Dive | Standard Vs FIFO and Use Cases
Rory  West

Rory West

1624231020

A Dummies Guide to using AWS SNS for Your Business Case

This article is part of Cloud for Dummies series . I tend to explain things in layman terms and not If you are interested in other topics that I have covered on Cloud , please check out my other articles .Before we proceed further I assume the following .

i. You have some idea of AWS and

ii. have a AWS account to conduct the tutorial if you wish to

As part of this article , we will get an understanding on the following topics.

a. What is SNS ?

b. What is a Pub-Sub model ?

c. What is a topic ?

d. What are the different types of subscribers to a SNS topic ?

e. Various controls you can apply to a SNS topic .

Also, we will have a hands on tutorial implementing what we learnt.

#aws #sns #cloudfordummies

A Dummies Guide to using AWS SNS for Your Business Case

Dynamic AWS S3 Notification Configuration using Terraform

It is the simple stuff that you expect to be, well, simple. Until they aren’t.

So the situation is like this:

  • I have an aws s3 bucket
  • I have multiple dynamically created consumers for objectCreated event from this bucket
  • Each consumer subscribes to specific prefix on this bucket. i.e. service 1 will listen to new files on srv1/ path only. service2 will listen to new files on srv2/ path only and so on.

Since one SNS cannot differentiate between s3 prefixes, I need to have multiple SNS topics — one for each service

Doing it manually — it is super easy, just create another pair of sns/sqs and I’m ready to go. But manual process belongs to the dark ages of 1995, I need to do it automatically using IaaC, Terraform in this case.

#terraform #aws #sns #s3

Dynamic AWS S3 Notification Configuration using Terraform

Data Visualization to our rescue!

In my article Analysis for Everything?, you got an insight into what data analysis is and what steps are taken to carry it out.

In my previous article, you saw the statistics background required to start with data analysis.

Well, this time I thought to give a twist to my articles by adding more ‘technical’ content. YES, we are going to discuss Python codes, the functions, and the math that goes behind them.

Hey wait, don’t get all bored already! Alright fine, let me tell you a story and maybe make it interesting :)

The quick story…

So there was this girl named Mishu, who visited her grandmother’s house frequently during spring or let’s say early summers. Her grandmother’s place had a backyard that had a variety of flowers, fruits, and vegetables.

But, Mishu was always mesmerized by the Iris flowers that bloomed during the spring. Her grandmother told her that there were three types of iris in the backyard and they differ through some features only. She just couldn’t identify the flowers like her grandmother, so her curiosity peaked even more.

Mishu is smart and good with numbers unlike us, so she decided to research the types of iris flowers mentioned by her grandmother. She found that these three species are: setosa, virginica, and versicolor. She even found a dataset that gave her sepal length, sepal width, petal length, and petal width of the species.

After making careful observations she saw the variations in the numbers and decided to plot the data using graph paper manually. It took her days to do so, but she finally fathomed that lengths differed for different species, that her grandmother had perceived through observation. Well, the approach used by Mishu was tedious, took time, and might seem naive. But hey, that’s what helps us to come to a starting logic and start with the tech part of anything.

Let us level this up and come back to our dear friend ‘programming’ to help us carry out the data visualization process.

import numpy as np 
import pandas as pd 
import seaborn as sns
import matplotlib.pyplot as plt
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

#data-analysis #data-science #data-visualization #iris-dataset #sns

Data Visualization to our rescue!

Messaging in AWS Using SNS and SQS

Learn how to use asynchronous messaging in AWS using SNS and SQS.

There are two main communication paradigms in event-driven architectures used in microservices design.

  • Queueing provides a messaging system to integrate two different services.
  • Publish/subscribe messaging is a form of asynchronous service-to-service communication used in microservices architectures. In contrast to queueing, publish/subscribe messaging allows multiple consumers to receive each message in a topic.

They allow us to de-couple producers and consumers of messages. By combining publish/subscribe messaging systems with queueing systems, we can build fault-tolerant, scalable, resilient, and reactive application architectures. Amazon Web Services (AWS) offers a number of services which provide these two communication paradigms. In this article, we will learn how to program AWS services – Simple Notification Service (SNS) for publish/subscribe messaging and Simple Queue Service (SQS) for queueing using AWS SDK in Java.

#java #aws #terraform #sqs #sns

Messaging in AWS Using SNS and SQS
笹田  晃

笹田 晃

1597953600

【全リージョン対応】EventBridge + SNS + Chatbotで GuardDutyの結果を Slackチャンネルに通知する

GuardDutyの通知方法について

Amazon GuardDuty はマネージドな 脅威検出サービス です。 VPCフローログ、AWS CloudTrail イベントログ、DNSログを分析し、 悪意のあるアクティビティを検出します。早急なセキュリティ対応に役立ちます。

GuardDutyは サポートされている全てのリージョンで有効化 が強く推奨されています。

さて、全リージョンで有効化した後に考えないといけないのは GuardDutyで検出された結果の通知方法 です。

Amazon SNS を活用して特定の Eメールに飛ばす方法や、他 3rdパーティのツールを活用する方法などあります。 (参考: 一発でGuardDutyを全リージョン有効化して通知設定するテンプレート作った | Developers.IO)

AWS Chatbotを使った通知がオススメ

普段 Slackを業務で使っている方 には、 AWS Chatbot を利用した通知がオススメです。 Chatbot は最近 GAされたサービスです。AWSのアラートなどをトリガーに、 Slackチャンネルや Amazon Chime チャットルームに通知を簡単に飛ばしてくれます。

GuardDutyで出てきた結果を Slackの特定のチャンネルに飛ばすことができます。

  • GuardDutyの結果は Amazon CloudWatch Events のイベントとして、利用できます
  • Amazon EventBridge を使って、このイベントをトリガーに SNS通知を行う設定をします
  • Chatbot を使って SNS通知を Slackチャンネルに通知します

構築してみた

「GuardDutyの結果を Slackチャンネルに通知する構成」を 全リージョンに展開 してみます。

#aws #sns #guardduty #eventbridge #aws chatbot

【全リージョン対応】EventBridge + SNS + Chatbotで GuardDutyの結果を Slackチャンネルに通知する
Ida  Nader

Ida Nader

1597678920

From Legacy Application to Serverless With EventBridge

Most startup applications are built with the intention to use the modern technologies with the intention to save time and money and make the application better than your competitors’.

However, once modern applications will at some point become a legacy burden. It will then be easy to assume that disposing of the old technology and building something new will solve all the issues. Yet, many times the old application still holds information that is crucial for the business survival.

So, depending on the application’s condition and the team behind it, any intervention might be risky and expensive.

Also, it can very often happen that there is almost no documentation and most of the people that started it, already left the company and there is nobody to consult with.

Moreover, stakeholders might reject the idea to change the system that works, without some serious reasons.

Again, depending of the circumstances, you need to find the right strategy. You need to allow overall IT business to progress, so not to lose customers but to gain customer.

In our case, the idea was to just start switching off the lights in the old infrastructure ,one by one, and moving pieces of old business logic into the modern cloud infrastructure.

A legacy monster which was hanting us…

I believe that in most software solutions (couple of years old), there is a monster with serious technical depth. At the beginning, it was aimed to be just a simple CMS. However, as the business progressed, the app constantly grew and nobody really cared about documentation nor the technical depth that much.

Over the years, the CMS had so much integrations with 3rd party applications so nobody could clearly explain how the integrations work anymore. Even worse, some of the integrations that weren’t useful anymore, remained in production as nobody was sure if they will break something else by removing it.

In parallel, the business thrived and required modernization of the existing solution. Therefore, there was a set of independent projects based on serverless architecture that consisted of microservices and micro frontends.

Image for post

However, modern applications were not aware of some crucial user states. For example, they didn’t know if a user was a paying user and which subscription package did they bought.

#aws #event-driven-architecture #serveless #sns #eventbridge

From Legacy Application to Serverless With EventBridge
Ida  Nader

Ida Nader

1596085260

Send SMS With Amazon SNS (Simple Notification Service) Using PHP

In this article, I will show you how to send SMS to any country user using Amazon SNS (Simple Notifications Service) using PHP.

**Code available in GitHub @ **Send SMS With Amazon SNS

We will cover

  1. AWS Create New User & Give SNS Policy Access
  2. Folder Structure
  3. Downloading AWS PHP SDK
  4. Implementation
  5. Upgrading Daily Limit

Prerequisites

Basic knowledge of PHP. If you need hands-on experience then better to set up your AWS account.


Step 1 - AWS Create New User & Give SNS Policy Access

First log in to your AWS account and in the top navigation under services feature, search for **IAM** as shown below

AWS | Search IAM

AWS | Search IAM

Once you are in the **IAM** page. Navigate to User section on the left sidebar and click on **New User **as shown below

AWS IAM | Create New User

AWS IAM | Create New User

Now in Add User page, we need to add user detail and set up the as following

AWS New User Form Details

AWS New User Form Details

NOTE: Please check on Programmatic Access else it won’t work when you start using in your code.

Once you click on Next button its time to setup Permissions as follows

Attach Existing Policies -> Search (SNS) -> Select (Amazon SNS Full Access)

Attach Permission | Amazon SNS Full Access

Attach Permission | Amazon SNS Full Access

Next, you can add **tags** so that it will help you to remember for which purpose you had created this user, you can skip adding tags.

If you skip tags then it will take you to final step ie **Review **to check if everything is proper as follows

AWS New User Review Page

#php #sns

Send SMS With Amazon SNS (Simple Notification Service) Using PHP