Accessing variable from another module with for each

I’m using a module to create aws sns resources, another module to create aws cloudwatch alarm resources, and trying to to access the value of the sns topic arn of the former from the latter.

But, I am using for_each in the root’s main.tf as I have multiple clusters.

resource "aws_sns_topic" "set_topic_for_cloudwatch_alarms" {
  name = "monitoring"
}

output "set_rds_topic_arn" {
  value = aws_sns_topic.set_topic_for_cloudwatch_alarms.arn
}

main.tf

locals {
  cluster_configurations = {
    for key, cluster in var.rds_clusters : key => {
      cluster_identifier = cluster.cluster_identifier
      engine_mode = cluster.engine_mode
      sns_set_topic_name   = "${cluster.cluster_identifier}-${var.rds_set_environment_name}-monitoring-topic"
    }
  }
}

# SNS topic
module "sns_topic" {
  source     = "../../modules/sns_topic"
  
  for_each = local.cluster_configurations
  
  sns_set_topic_name = each.value.sns_set_topic_name

}


# Cloudwatch alarms
module "cloudwatch_alarms" {
  source = "../../modules/cloudwatch_monitoring_rds"

  for_each = local.cluster_configurations

  rds_set_cluster_identifier      = "auroracluster1" //To be updated
  rds_set_engine_mode      =  "auroracluster1" //To be updated
  rds_set_environment_name       =  "auroracluster1" //To be updated
  set_rds_topic_arn = module.sns_topic.set_rds_topic_arn --------> This doesn't work
}

I want to know how to call that module.
Error:

│ Error: Unsupported attribute

│ on main.tf line 37, in module “cloudwatch_alarms”:
│ 37: set_rds_topic_arn = module.sns_topic.set_rds_topic_arn[0]
│ ├────────────────
│ │ module.sns_topic is object with 2 attributes

│ This object does not have an attribute named “set_rds_topic_arn”.

Hi @rbharadwaj042,

Because you are now creating multiple instances of module.sns_topic, that is now an object with keys matching the for_each values, so you will need to specify how you want to access each of those instances. Given that these both have the same for_each argument, I would assume you want to get the corresponding output from the same key, in which case you could use

set_rds_topic_arn = module.sns_topic[each.key].set_rds_topic_arn