Amazon Simple Notification Service (SNS) is a flexible, fully managed messaging service that enables you to send messages to a large number of recipients. In this tutorial, we will walk you through the process of setting up SNS with Terraform, a popular infrastructure as code (IaC) tool.

Why Use Terraform with SNS?

Using Terraform with SNS allows you to automate the process of creating and managing your SNS resources. With Terraform, you can define your SNS resources in code, making it easy to version control and reuse your configurations. Additionally, Terraform integrates with a number of cloud providers, including AWS, so you can use a single tool to manage your entire infrastructure.

Prerequisites

Before we get started, you’ll need to make sure you have the following:

  • An AWS account
  • Terraform installed on your local machine
  • AWS credentials configured on your local machine

Step 1: Create an IAM Policy for SNS

Before you can use SNS with Terraform, you’ll need to create an IAM policy that allows you to access SNS. To do this, log in to the AWS Management Console and navigate to the IAM dashboard.

From the dashboard, click on “Policies” in the left-hand menu, and then click the “Create policy” button.

On the “Create policy” page, select the “JSON” tab and paste the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sns:*",
            "Resource": "*"
        }
    ]
}

This policy grants full access to all SNS resources. You can customize the policy to grant more granular permissions if desired.

Once you’ve pasted the policy, give it a name and description, and then click the “Create policy” button.

Step 2: Create an IAM User

Next, you’ll need to create an IAM user that has the necessary permissions to access SNS. To do this, click on the “Users” menu item in the left-hand menu and then click the “Add user” button.

On the “Add user” page, give your user a name and select the “Programmatic access” checkbox. This will generate an access key and secret access key for the user, which you’ll use to authenticate with AWS.

Under “Set permissions,” select the “Attach existing policies directly” option and then select the SNS policy you created in step 1.

Click the “Create user” button to create the user. Make sure to save the access key and secret access key for later use.

Step 3: Set Up Terraform

With your IAM policy and user in place, you’re ready to set up Terraform. First, create a new directory for your Terraform configuration and navigate to it in your terminal.

Next, create a file called main.tf and paste the following code:

provider "aws" {
  access_key = "ACCESS_KEY"
  secret_key = "SECRET_KEY"
  region     = "REGION"
}

Replace ACCESS_KEY and SECRET_KEY with the access key and secret access key for your IAM user, and replace REGION with the region you want to use (e.g. “us-east-1”).

Step 4: Create an SNS Topic

With your Terraform configuration set up, you can now start creating SNS resources. The first resource you’ll create is an SNS topic.

To create an SNS topic, add the following code to your main.tf file:

resource "aws_sns_topic" "example" {
  name = "example-topic"
}

This code creates an SNS topic with the name “example-topic”. You can customize the name to your liking.

Step 5: Create an SNS Subscription

Now that you have an SNS topic, you can create an SNS subscription to the topic. An SNS subscription allows you to specify a protocol and endpoint where SNS can send messages.

To create an SNS subscription, add the following code to your main.tf file:

resource "aws_sns_subscription" "example" {
  topic_arn = aws_sns_topic.example.arn
  protocol  = "EMAIL"
  endpoint  = "EMAIL_ADDRESS"
}

Replace EMAIL_ADDRESS with the email address you want to receive messages at. You can also change the protocol to one of the other supported protocols, such as SMS or HTTPS.

Step 6: Initialize and Apply Your Configuration

With your SNS resources defined in code, you’re ready to initialize and apply your configuration.

To initialize your configuration, run the following command:

terraform init

This command installs the necessary plugins for Terraform to manage your AWS resources.

Next, run the following command to create your SNS resources:

terraform apply

This command will create your SNS topic and subscription, and output the ARN for your SNS topic.

Step 7: Publish a Message to Your SNS Topic

Now that you have your SNS topic and subscription set up, you can use the AWS CLI to publish a message to the topic.

First, make sure the AWS CLI is installed on your local machine. Then, run the following command to publish a message to your SNS topic:

aws sns publish --topic-arn ARN --message "This is a test message"

Replace ARN with the ARN of your SNS topic, which you can find in the output of the terraform apply command.

You should receive the message at the email address or endpoint specified in your SNS subscription.

Step 8: Create an SNS Topic Policy

An SNS topic policy allows you to specify which AWS accounts and principals can access your SNS topic.

To create an SNS topic policy, add the following code to your main.tf file:

resource "aws_sns_topic_policy" "example" {
  arn      = aws_sns_topic.example.arn
  policy   = <<POLICY
{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "SNS:Publish",
      "Resource": "arn:aws:sns:REGION:ACCOUNT_ID:example-topic"
    }
  ]
}
POLICY
}

This code creates an SNS topic policy that allows any AWS account to publish messages to your SNS topic. Replace REGION and ACCOUNT_ID with your own values.

Step 9: Create an SNS Topic Subscription

In addition to creating subscriptions to your SNS topic, you can also create subscriptions to other SNS topics. This is useful for creating a publish-subscribe model, where one topic publishes messages that are then delivered to multiple subscribers.

To create an SNS topic subscription, add the following code to your main.tf file:

resource "aws_sns_topic_subscription" "example" {
  topic_arn = "ARN"
  protocol  = "EMAIL"
  endpoint  = "EMAIL_ADDRESS"
}

Replace ARN with the ARN of the SNS topic you want to subscribe to, and replace EMAIL_ADDRESS with the email address, you want to receive messages at.

Step 10: Destroy Your SNS Resources

When you’re finished with your SNS resources, you can use Terraform to destroy them. To do this, run the following command:

terraform destroy

This command will delete your SNS topic, subscription, and any other SNS resources you created.

Conclusion

In this tutorial, you learned how to set up SNS with Terraform. With this setup, you can easily automate the process of creating and managing your SNS resources, making it easier to build and scale your messaging systems.