Creating multiple AWS SNS topic and subscriptions

Hi,

I’m trying to create a module that will create multiple AWS SNS topics and subscriptions. I can create multiple topics no problem, but when trying to create the subscriptions to use the topics ARN I’m getting an error.

Inappropriate value for attribute "topic_arn": string required.

The code I am using is below -

main.tf
resource “aws_sns_topic” “this” {
count = var.create_sns_topic && length(var.name) > 0 ? length(var.name) : 0
name = var.name[count.index]
display_name = var.display_name
}

resource “aws_sns_topic_subscription” “this” { count = var.create_sns_topic && length(var.name) > 0 ? length(var.name) : 0
topic_arn = aws_sns_topic.this[count.index]
protocol = “var.protocol”
endpoint = “var.endpoint”
}

outputs.tf
output “sns_topic_arn” {
description = “ARN of SNS topic”
value = aws_sns_topic.this.*.arn
}

variables.tf
variable “create_sns_topic” {
type = bool
default = true
}
variable “name” {
type = list(string)
default = [“test1”, “test2”, “test3”]
}
variable “display_name” {
type = string
default = “test”
}

Can anyone offer any advice?

Maybe aws_sns_topic.this[count.index].arn?

Thank you! Its worked.

what do you have in var.endpoint. I have multiple sqs queues. I referred to your code and wanted to create multiple sns subscriptions to sqs queues. here is my code

resource “aws_sns_topic_subscription” “sns_topics_subscriptions” {
count = var.create_sns_topic && length(var.topic_name) > 0 ? length(var.topic_name) : 0
topic_arn = aws_sns_topic.sns_topics[count.index].arn
protocol = “sqs”
endpoint = aws_sqs_queue.queue_name[count.index].arn

}
Can you please advice?

here is the error Im getting:

on sns.tf line 44, in resource “aws_sns_topic_subscription” “queue_name”:
44: endpoint = aws_sqs_queue.queue_name[count.index].arn

A managed resource “aws_sqs_queue” “queue_name” has not been declared in the
root module.

@rgopannagari
Error Messages says that you have not defined aws_sqs_queue called queue_name.

Since you don’t mention you are creating SQS Q’s or they are already present let’s assume they are present.

you have to read the existing Q’s and then use them, you can do it as given below.

# List of the SQS Q's
variable "sqs_q_names" {
  type = list(string)
  default = [
    "name_of_sqs_q_1",
    "name_of_sqs_q_2",
    "name_of_sqs_q_n"
  ]
}

# Look for the Q's
data "aws_sqs_queue" "sqs" {
  count = length(var.sqs_q_names) > 0 ? length(var.sqs_q_names) : 0
  name = var.sqs_q_names[count.index]
}

resource "aws_sns_topic_subscription" "sns_topics_subscriptions" {
  count = length(var.sqs_q_names) > 0 ? length(var.sqs_q_names) : 0
  #
  # use your other code here
  #
  endpoint = data.aws_sqs_queue.sqs[count.index].arn
}