How to create AWS SNS using Terraform

background
Reading Time: 3 minutes

Hi all, In this blog we are going to create AWS SNS(Simple Notification Service) using Terraform. We will be going to create SNS topic, then we will also be creating topic subscription using Terraform.

Provider

Firstly we will be providing the provider details. Here i am going with aws provider with region us-east-1.

provider "aws" {
  region = "us-east-1"
}

Resource

aws_sns_topic

We are going to use one terraform resource known as aws_sns_topic to create a topic whith the name of your choice. In this blog i am going with very simple topic for sns, with no extra optional arguments. In the coming blogs we will be seeing it in detail.

resource "aws_sns_topic" "user_updates" {
  name = "test-2"
  
}

Here you can see above, i am using name test-2. you can use according to yourself. This will create a standard topic.

Here in the above picture, you can see that the code has created our sns topic, but still the topic subscription is missing. In the next resource below we are going to create subscription also.

aws_sns_topic_subscription

Now we will be using aws_sns_topic_subscription resource to add subscription to your topic. Here i am using email as protocol you can many from the list as shown below.

Now, we will have to know the arn of our topic to tell this resource that we need this subscription for the specified topic. For that we are going to use data source.

data "aws_sns_topic" "example" {
  name = "test-2"
}

resource "aws_sns_topic_subscription" "user_updates_sqs_target" {
  topic_arn = data.aws_sns_topic.example.arn
  protocol  = "email"
  endpoint  = "apriyadarshi407@gmail.com"
}

The data source will grab the arn of your newly created sns topic. As soon as it grabs the arn we will be using the output in our topic_arn argument as shown in above code.

Now you will get a mail to your specified end-point for subscription approval. Approve it and refresh your aws console you will get to see that your subscription has been added successfully.

Conclusion

In this blog we have learned how to create aws sns using terraform. We created topic and then grab the arn using data source and finally created subscription to that topic also.

To know more about SNS visit https://aws.amazon.com/sns/

Visit https://blog.knoldus.com/tag/aws/ for more blogs on AWS

Leave a Reply