
This assumes you have already configured the aws command line tool. If not, check out my article on Getting Started with the AWS CLI.
A Simple Notification Service (SNS) Topic can be used to create notification alerts, such as an email notification. This uses the messaging services pub sub model.
- pub (publish) - create a new alert in a Topic
- sub (subscribe) - get alerts in a Topic
The aws sns list-topics command can be used to list your Simple Notification Service (SNS) Topics.
aws sns list-topics
Something like this should be returned.
{
"Topics": [
{
"TopicArn": "arn:aws:sns:us-east-1:123456789012:myTopic.fifo"
}
]
}
And the aws sns list-subscriptions command can be used to list the subscriptions to the topic. In this example, John Doe is subscribed to the topic, so John Doe should get an email when a message is put on the topic.
~]$ aws sns list-subscriptions
{
"Subscriptions": [
{
"SubscriptionArn": "arn:aws:sns:us-east-1:123456789012:mytopic:0f8966a4-1bf9-48fa-8564-5b4ecab489c2",
"Owner": "123456789012",
"Protocol": "email",
"Endpoint": "john.doe@example.com",
"TopicArn": "arn:aws:sns:us-east-1:123456789012:mytopic"
}
]
}
The aws sns publish command can be used to publish a message to the topic, which in this example should send an email to john.doe@example.com.
~]$ aws sns publish --subject Hello --message World --topic-arn arn:aws:sns:us-east-1:123456789012:mytopic
{
"MessageId": "3756dea6-80cd-5e4a-ba9a-80a33a856481"
}
The IAM role associated with the user attempting to publish the message will need to allow sns:Publish.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": "*"
}
]
}
Or, if you are subscribing a Lambda Function to one of your SNS Topics, the aws lambda add-permission command can be used to allow the SNS Topic to invoke the Lambda Function.
aws lambda add-permission \
--function-name sendgrid \
--source-arn arn:aws:sns:us-east-1:12346789012:my-topic \
--statement-id allow-sns-to-invoke-lambda \
--action "lambda:InvokeFunction" \
--principal sns.amazonaws.com
This command attaches the following IAM Policy to the Lambda Function, allowing the SNS Topic to invoke the Lambda Function.
{
"Version": "2012-10-17",
"Id": "default",
"Statement": [
{
"Sid": "allow-sns-to-invoke-lambda",
"Effect": "Allow",
"Principal": {
"Service": "sns.amazonaws.com"
},
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:my-lambda-function",
"Condition": {
"ArnLike": {
"AWS:SourceArn": "arn:aws:sns:us-east-1:123456789012:my-sns-topic"
}
}
}
]
}
Did you find this article helpful?
If so, consider buying me a coffee over at