I have an existing AWS CloudFormation stack that has an Amazon SNS topic resource, and I want to subscribe the Amazon SQS queue in a different stack to subscribe to the SNS topic from the other stack. How do I do that?

If both the SNS topic and SQS queue are in the same stack, the process is simpler; see Using an AWS CloudFormation Template to Create a Topic that Sends Messages to Amazon SQS Queues. However, if the SNS topic and SQS queue are in two separate stacks, this cause a race condition.

To avoid this, use CloudFormation custom resources:

1.    In the SNS stack, use the ARN of the SNS topic as an output, similar to the following:

"Outputs" : {

    "SnsTopicName" : {

        "Value" : {"Ref" : "SNStopic"}

    }

}

2.    Create a Lambda function resource that describes the SNS stack and retrieve the values from the outputs of the SNS stack.

3.    In the SQS stack, create a custom resource that gets the SNS ARN from the SNS stack, similar to the following (note: the example preassumes that the logical name you chose in the last preceding step was “LambdaReturnSNSARN”):

"GetSNSTopicName" : {

    "Type": "Custom::GetSNSTopicName",

    "Properties": {

        "ServiceToken": {"Fn::GetAtt": ["LambdaReturnSNSArn", "Arn"]},

        "StackName": {"Ref": "SnsStackName"}

    }

},

4.    In the same SQS stack, create another custom resource that subscribes the SQS queue to the SNS topic, similar to the following:

"SubscribeSNS" : {

    "Type": "Custom::SubscribeSNS",

    "Version" : "1.0",

    "Properties" : {

        "ServiceToken" : {"Fn::GetAtt": ["LambdaSubscribeSNS", "Arn"]},

        "SNSarn" : {"Fn::GetAtt": ["GetSNSTopicName", "SnsTopicName"]},

        "SQSarn" : {"Fn::GetAtt": ["MySQS", "Arn"]}

    }

},

5.    Create a Lambda function resource that uses the parameter values that are passed to "SNSarn" and "SQSarn" and subscribes the SQS queue to the SNS topic from another stack.


Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2016-08-24
Updated: 2017-05-04