hendry
hendry

Reputation: 10843

Re-using an existing SNS Topic in a Cloudformation template

I have a SAM cloudformation template:

Transform: AWS::Serverless-2016-10-31
Description: Create SNS with a sub

Parameters:
    NotificationEmail:
        Type: String
        Description: Email address to subscribe to SNS topic

Resources:
    NotificationTopic:
        Type: AWS::SNS::Topic
        DeletionPolicy: Retain
        Properties:
            TopicName: sam-test-sns
            Subscription:
                - Endpoint: !Ref NotificationEmail
                  Protocol: email

Outputs:
    SNSTopic:
        Value: !Ref NotificationTopic

So I want to keep the topic sam-test-sns around since there are several subscribers already, and I don't want subscribers to tediously re-subscribe if I tear down the service and bring it back up.

Tearing down the service with Retain keeps the topic around, so that's fine. But when I try deploy the template, it fails because it already exists.

SNS already exists

So what is the right approach to use an existing SNS topic?

Upvotes: 0

Views: 3305

Answers (2)

Chris Williams
Chris Williams

Reputation: 35238

With the output done you are exporting the variable. I am going to assume you want this resource in another stack.

First you need to export the value so for example

Outputs:
    SNSTopic:
        Value: !Ref NotificationTopic
    Export:
        Name: Fn::Sub: "${AWS::StackName}-SNSTopic"

Add a parameter to your new stack of SNSStackName, where you would pass in the SNS stacks name (within the current region).

Then from within your new stack to reference you would need to call the output value like below:

Fn::ImportValue:
     Fn::Sub: "${SNSStackName}-SNSTopic"

Upvotes: 1

Christian
Christian

Reputation: 576

Keeping the "Ec2NotificationTopic" resource in the template after removing the stack but keeping the topic around, will instruct CloudFormation to also create the topic when (re)creating the stack, which will always fail.

Since you are just referencing an existing topic, you should remove the resource from the template and replace the references to it with the ARN/name.

Upvotes: 2

Related Questions