How to add email subscribers to an AWS SNS topic with Terraform

Bjorn Krols

Bjorn Krols

Published on
30 September 2021
locals {
  emails = ["hello@world.com"]
}

resource "aws_sns_topic" "topic" {
  name            = "my-topic"
  delivery_policy = jsonencode({
    "http" : {
      "defaultHealthyRetryPolicy" : {
        "minDelayTarget" : 20,
        "maxDelayTarget" : 20,
        "numRetries" : 3,
        "numMaxDelayRetries" : 0,
        "numNoDelayRetries" : 0,
        "numMinDelayRetries" : 0,
        "backoffFunction" : "linear"
      },
      "disableSubscriptionOverrides" : false,
      "defaultThrottlePolicy" : {
        "maxReceivesPerSecond" : 1
      }
    }
  })
}

resource "aws_sns_topic_subscription" "topic_email_subscription" {
  count     = length(local.emails)
  topic_arn = aws_sns_topic.topic.arn
  protocol  = "email"
  endpoint  = local.emails[count.index]
}

You will receive an email to confirm your subscription:

AWS SNS email subscription confirmation

Legacy method

Support for the email protocol was added to the aws_sns_topic_subscription resource in February 2021.

Before that, you had to use the following workaround to add email subscribers to an SNS topic:

resource "null_resource" "topic_email_subscription" {
  triggers = {
    topic_arn = aws_sns_topic.topic.arn
    emails    = sha1(jsonencode(local.emails))
  }
  count    = length(local.emails)
  provisioner "local-exec" {
    command = "aws sns subscribe --topic-arn ${aws_sns_topic.topic.arn} --protocol email --notification-endpoint ${local.emails[count.index]} --region ${data.aws_region.current.name} --profile ${local.profile}"
  }
}

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this