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

How to write the cloudformation subscription between Sns event topic and sqs event queue


I have A service where we have sns topics and in B service sqs queue event.

from B service cloud formation I need to write the cloud formation YAML file to subscription between SNS event topic and SNS event queue.

sns topic name : sns-event-topic

subscribed to queue name: abcd-events

Resources:

AbcdEventQueue:
    Type: "AWS::SQS::Queue"
    Properties:
      QueueName: "abcd-events"
AbcdEventQueuePolicy:
  Type: "AWS::SQS::QueuePolicy"
    Properties:
      Queues:
        - Ref: "AbcdEventQueue"
      PolicyDocument:
        Statement:
          - Effect: "Allow"
            Principal:
              AWS: '*'
            Action:
              - sqs:SendMessage
              - sqs:ReceiveMessage
              - sqs:DeleteMessage
              - sqs:GetQueueUrl
              - sqs:GetQueueAttributes
              - sqs:ListQueueTags
              - sqs:ChangeMessageVisibility
            Resource:
              - !GetAtt AbcdEventQueue.Arn


Solution

  • Assuming you have the SNS topic already you would create a AWS::SNS::Subscription resource.

    It would look like the below structure

    Subscription:
        Type: 'AWS::SNS::Subscription'
        Properties:
          TopicArn: !Ref TopicArn #You will need to provide the SNS Topic Arn here
          Endpoint: !GetAtt 
            - AbcdEventQueue
            - Arn
          Protocol: sqs
          RawMessageDelivery: 'true'
    

    If the SNS topic does not share the same stack you will need to pass this into your template, this can be done either as a parameter or by using the Export feature to define a global value that you can use by referencing it with the Fn::ImportValue intrinsic function.