Search code examples
amazon-web-servicesaws-cloudformationamazon-sqsamazon-sns

aws cloudformation template sns sqs


I've defined an SNS topic, an SQS queue, and an SNS subscription resource in a Cloudformation stack. All three are in the same stack, same region, and same AWS account.

Resources:
  SqsQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: 'some-queue'
  SnsTopic:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: 'some-topic'
  SnsSubscription:
    Type: AWS::SNS::Subscription
    Properties:
      Endpoint: !GetAtt [SqsQueue, Arn]
      Protocol: sqs
      TopicArn: !Ref SnsTopic

When I run the stack, all three resources are created successfully, but when I publish a message from SNS, it's never received by the SQS queue.

I've been following this link (https://aws.amazon.com/premiumsupport/knowledge-center/sqs-sns-subscribe-cloudformation/) and to my knowledge I've done everything I've needed to. What else am I missing?

Thanks!

Additional info

  • If I delete the subscription that Cloudformation created via the console and then create a new one via the console, messages are published fine. So it must be something incorrect about the subscription.

  • I used the AWS CLI to compare the properties of the subscription created by the Cloudformation template to the one created by the console. They are the exact same.


Solution

  • You need to add a policy to allow the SNS topic to publish to your queue. Something like this:

      SnsToQueuePolicy:
        Type: AWS::SQS::QueuePolicy
        Properties: 
          Queues:
            - !Ref SqsQueue
          PolicyDocument: 
            Version: '2012-10-17'
            Statement:
              - Sid: allow-sns-messages
                Effect: Allow
                Principal: '*'
                Resource: !GetAtt SqsQueue.Arn
                Action: SQS:SendMessage,
                Condition: 
                  ArnEquals:
                    aws:SourceArn: !Ref SnsTopic