Search code examples
amazon-web-servicesyamlaws-cloudformationsam

Subscribe SNS by SQS sam yaml


Here is sam yaml snippet:

  SnsTopic:
    Type: AWS::SNS::Topic
    Properties:
      DisplayName: !Sub ${Env}-sns-topic
      TopicName: !Sub ${Env}-sns-topic

  Queue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub ${Env}-queue
      VisibilityTimeout: 300
      MessageRetentionPeriod: 1209600
      ReceiveMessageWaitTimeSeconds: 20
      RedrivePolicy:
        deadLetterTargetArn: !GetAtt Dlq.Arn
        maxReceiveCount: 5

  Dlq:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub ${Env}-dlq
      VisibilityTimeout: 300
      MessageRetentionPeriod: 1209600
      ReceiveMessageWaitTimeSeconds: 0

  TestSubscription:
    Type: AWS::SNS::Subscription
    DependsOn: 
      - SnsTopic
      - Queue
      - Dlq
    Properties:
      Protocol: sqs
      TopicArn: !Ref SnsTopic
      Endpoint: !GetAtt 
        - Queue
        - Arn
      RawMessageDelivery: true

I am trying to create an SNS that is subscribed to an SQS with a Dead Letter Queue (DLQ). After deployment, I can see that the SNS and SQS have been created successfully, but the SQS subscription to the SNS does not appear to be working. When I check the subscriptions for the SQS, I can see that the SNS that was created in the same stack is listed, but I have to manually add the subscription for it to work. I'm wondering what could be causing this issue or if there's something missing in my example.


Solution

  • You have to setup AWS::SQS::QueuePolicy to allow SNS to send messages to the queue. Check AWS docs for examples of how to do it.