Carova

Serverless AWS SQS Queue Subscribed To SNS Topic

Create SQS Queue that received messages from SNS Topics through Subscribing your SQS Queue to the SNS Topic with an SQS Queue Policy. Bonus: Included is an AWS Lambda Function that is triggered by the SQS Queue.

Add the following to the resources section of your Serverless YAML file:

1 2 3functions: 4 QueueHandler: 5 handler: src/events/index.QueueHandler 6 events: 7 - sqs: 8 arn: { Fn::GetAtt: [QueryQueue, Arn] } 9 batchSize: 1 10 filterPatterns: 11 - messageAttributes: 12 event_type: 13 stringValue: [queryResponse] 14 iamRoleStatements: 15 - Effect: Allow 16 Action: 17 - sqs:ReceiveMessage 18 - sqs:DeleteMessage 19 - sqs:GetQueueAttributes 20 Resource: 21 - { Fn::GetAtt: [QueryQueue, Arn] } 22 - Effect: Allow 23 Action: 24 - sns:publish 25 Resource: 26 - { Ref: QuerySnsTopic } 27 iamRoleStatementsInherit: true 28 29resources: 30 Resources: 31 QuerySnsTopic: 32 Type: AWS::SNS::Topic 33 Properties: 34 TopicName: ${self:service}-${opt:stage, self:provider.stage}-query-topic 35 36 QueryQueue: 37 Type: AWS::SQS::Queue 38 DependsOn: 39 - QueryDLQ 40 Properties: 41 QueueName: ${self:service}-${opt:stage, self:provider.stage}-QueryQueue 42 RedrivePolicy: 43 deadLetterTargetArn: { Fn::GetAtt: [QueryDLQ, Arn] } 44 maxReceiveCount: 1 45 46 QueryDLQ: 47 Type: AWS::SQS::Queue 48 Properties: 49 QueueName: ${self:service}-${opt:stage, self:provider.stage}-QueryDLQ 50 MessageRetentionPeriod: 1209600 # 14 days in seconds 51 52 QueryQueuePolicy: 53 Type: AWS::SQS::QueuePolicy 54 DependsOn: 55 - QuerySnsTopic 56 - QueryQueue 57 Properties: 58 PolicyDocument: 59 Statement: 60 - Effect: Allow 61 Principal: '*' 62 Resource: { Fn::GetAtt: [QueryQueue, Arn] } 63 Action: 64 - SQS:SendMessage 65 - SQS:ReceiveMessage 66 Condition: 67 ArnEquals: 68 aws:SourceArn: 69 - { Ref: QuerySnsTopic } 70 Queues: 71 - { Ref: QueryQueue } 72 73 QueryQueueSnsSubscription: 74 Type: AWS::SNS::Subscription 75 DependsOn: 76 - QuerySnsTopic 77 - QueryQueue 78 Properties: 79 TopicArn: { Ref: QuerySnsTopic } 80 Endpoint: { Fn::GetAtt: [QueryQueue, Arn] } 81 Protocol: sqs 82 RawMessageDelivery: true