0

I have been trying to create SNS topic and publishing messages to those topics? But after deploying on dev, I get error 'Topic doesn't exist'?

SNS Topic SAM code:

    ItemServiceTopic:
        Type: AWS::SNS::Topic
        Properties:
            DisplayName: 'ItemServiceTopic'
            FifoTopic: true
            KmsMasterKeyId: !Ref KMSDecryptKey
            TopicName: 'item-service-dev-topic.fifo'

Lambda which will be used to publish messages to SNS

    PostItem:
        Type: AWS::Serverless::Function
        Properties:
            Handler: handlers/item-handler.postItem
            Layers:
                - !Ref NodeDependenciesLayer
            Events:
                PostItemApi:
                    Type: Api
                    Properties:
                        RestApiId: !Ref ItemServiceApiG
                        Path: /v0/items
                        Method: POST
            Policies:
                - AWSSecretsManagerGetSecretValuePolicy:
                    SecretArn: !Sub 'arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:ItemServiceSecrets-d768io'
                
                - KMSDecryptPolicy:
                    KeyId: !Ref KMSDecryptKey 

                - SNSPublishMessagePolicy:
                    TopicName: !Sub 'arn:aws:sns:${AWS::Region}:${AWS::AccountId}:item-service-topic.fifo'

Is there a way where the above error can be resolved ?

Note: I have added SNS to an existing SAM template file , but I feel its not creating the SNS and hence while running the 'postItem' handler it fails saying no SNS topic found

maafk
  • 6,176
  • 5
  • 35
  • 58
Aagam Doshi
  • 155
  • 2
  • 14
  • It sounds like your `AWS::Serverless::Function` had previously existed, and it is _updating_ the function first with a new policy _before_ the new SNS topic is created. Can you try and deploy first with the `SNSPublishMessagePolicy` commented out, then if successful, deploy again with the `SNSPublishMessagePolicy` in – maafk Nov 02 '20 at 12:47

1 Answers1

0

Try using a REF for the SNSPublishMessagePolicy

PostItem:
  Type: AWS::Serverless::Function
  Properties:
    Handler: handlers/item-handler.postItem
    Layers:
      - !Ref NodeDependenciesLayer
    Events:
      PostItemApi:
        Type: Api
        Properties:
          RestApiId: !Ref ItemServiceApiG
          Path: /v0/items
          Method: POST
    Policies:
      - AWSSecretsManagerGetSecretValuePolicy:
          SecretArn: !Sub "arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:ItemServiceSecrets-d768io"
      - KMSDecryptPolicy:
          KeyId: !Ref KMSDecryptKey
      - SNSPublishMessagePolicy:
          TopicName: !Ref ItemServiceTopic

This way Cloudformation should know that the update function needs to for the SNS topic to first exist before updating the lambda function

maafk
  • 6,176
  • 5
  • 35
  • 58