amazon-web-servicesterraformterraform-provider-awsamazon-sns

terraform conditional resource creation for_each and list


I am adding this to a module and would like to enable this resource only when a parent project (using the module) input one or a list of email addresses (so if "var.sns_email_subscriber" is not specified or none in the parent project, this resource won't be enabled/used).

resource "aws_sns_topic_subscription" "email_target" {
  for_each               = toset(var.sns_email_subscriber)
  topic_arn              = aws_sns_topic.sns_topic.arn
  protocol               = "email"
  endpoint               = each.value
  endpoint_auto_confirms = true
}

var.sns_email_subscriber is list(string)

Would someone be able to help? Thanks in advance.


Solution

  • You just need to provide a default value in the sns_email_subscriber variable declaration, of an empty list. The for_each won't create any resources if it is passed an empty list.