Crating SNS Topic and Subscription at the same time

I got below error by serverless deploy on aws.

An error occurred: SNSSubscription - Topic does not exist

It seems that this error is caused by creating sns subscription and
its related topic at the same time.

yml file is like below.

service: aws-sample

provider:
  name: aws
  runtime: nodejs8.10
  region: ap-northeast-1
  stage: dev

  environment:
      sqsUrl:
        Ref: SQSQueue
      snsArn:
        Ref: SNSTopic

  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
      Resource: "arn:aws:dynamodb:ap-northeast-1:*:*"

functions:
  clientCreate:
    handler: src/functions/client/handler.create
    events:
      - http:
          path: clients
          method: post
          cors: true
  clientFind:
    handler: src/functions/client/handler.find
    events:
      - http:
          path: clients/{id}
          method: get
          cors: true

resources:
  Resources:
    SQSQueue:
      Type: AWS::SQS::Queue
      Properties:
        QueueName: ${self:service}-${self:provider.stage}-queue

    SNSTopic:
      Type: AWS::SNS::Topic
      Properties:
        DisplayName: SNS Topic
        TopicName: ${self:service}-${self:provider.stage}-topic

    SNSSubscription:
      Type: AWS::SNS::Subscription
      Properties:
          Endpoint: email@provider.com
          Protocol: email
          TopicArn: { "Fn::Join" : ["", ["arn:aws:sns:${self:provider.region}:", { "Ref" : "AWS::AccountId" }, ":${self:resources.Resources.SNSTopic.Properties.TopicName}" ] ]  }

Are there any way to creating them with one deploy?

Thanks in advance.

1 Like

Finally, this issue was solved.

Please can you advise how did you solve this? I am still getting this error.

An error occurred: SNSSubscription - Topic does not exist

Thanks

You can solve this issue by writing yml file like below.

    SNSTopic:
      Type: AWS::SNS::Topic
      Properties:
        DisplayName: SNSTopic
        TopicName: ${self:service}-${self:provider.stage}-topic
        Subscription:
          - Protocol: SQS
            Endpoint: { “Fn::Join” : [“”, [“arn:aws:sqs:${self:provider.region}:“, { “Ref” : “AWS::AccountId” }, “:${self:resources.Resources.SQSQueue.Properties.QueueName}” ] ] }

Maybe, we should write Subscription section under Topic section.

Thanks

If you need to add a subscription to a topic before it’s created, you can do.

resources:
  Resources:
    SNSTopic:
       Type: AWS::SNS::Topic
       Properties:
         DisplayName: SNS Topic
         TopicName: SNSTopicName
    
    SNSSubscription:
      Type: AWS::SNS::Subscription
      Properties:
        TopicArn: {"Ref": "SNSTopic"}