Adding multiple emails to sns subscriptions using Terraform
We seldom find advanced topics on Terraform templates online and sometimes the information is not fully available on the Official Pages as well.
I'm bringing to you advanced template examples to be used in your organization's environment.
Bringing the first in the series is adding multiple email ID subscriptions to our SNS Topic.
While you all know the Terraform Basics, I would not go into much detail on them. I have structured the code in a parameterized manner and would be following the same pattern in all my posts.

# providers.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.60.0"
}
}
}
provider "aws" {
region = var.region
profile = var.profile
}
# variables.tf
variable "region" {}
variable "profile" {}
variable "sns-topic" {}
variable "sns-topic-subscription" {}
# locals.tf
locals {
emails = ["emailid1@email.com","emailid2@email.com","emailid3@email.com"]
}
# sns.tf
resource "aws_sns_topic" "sns_topic" {
name = var.sns-topic
}
resource "aws_sns_topic_subscription" "sns_topic_subscription" {
count = length(local.emails)
topic_arn = aws_sns_topic.sns_topic.arn
protocol = "email"
endpoint = local.emails[count.index]
}
# sns.tfvars
sns-topic = "sns-test-topic"
sns-topic-subscription = "sns-test-subscription"
profile = "aws-terraform"
region = "us-east-1"
The same can be achieved without the use of locals.tf as well. Then we use the "for_each" functionality and pass the values to it and then refer to the "value" in the endpoint section.
resource "aws_sns_topic_subscription" "sns_topic_subscription" {
for_each = toset(["emailid1@email.com","emailid2@email.com","emailid3@email.com"])
topic_arn = aws_sns_topic.sns_topic.arn
protocol = "email"
endpoint = each.value
}
And as you already know the drill... Run the Terraform template
$ terraform init
$ terraform plan
$ terraform apply -var-file sns.tfvars --auto-approve
$ terraform destroy -var-file sns.tfvars --auto-approve
Prerequisite:
Ensure AWS CLI is installed and configured. Installation: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
Configuration: (I have configured using "Short-term credentials" format) https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
Ensure Terraform is installed
https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli