How to Create an SNS Topic with Terraform: Simple Guide
To create an SNS topic in Terraform, use the
aws_sns_topic resource block with a unique name. This defines the topic in your AWS account and can be referenced in other resources.Syntax
The aws_sns_topic resource creates an SNS topic. You must provide a name for the topic. Optionally, you can set other properties like display_name for a friendly name.
- resource: declares a resource block
- aws_sns_topic: specifies the SNS topic resource type
- name: unique identifier for the topic
- display_name: optional friendly name shown in notifications
terraform
resource "aws_sns_topic" "example" { name = "my-topic" display_name = "My Topic" }
Example
This example creates an SNS topic named my-topic with a display name My Topic. After applying, Terraform will create the topic in AWS and output its ARN (Amazon Resource Name).
terraform
provider "aws" { region = "us-east-1" } resource "aws_sns_topic" "my_topic" { name = "my-topic" display_name = "My Topic" } output "sns_topic_arn" { value = aws_sns_topic.my_topic.arn }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
sns_topic_arn = arn:aws:sns:us-east-1:123456789012:my-topic
Common Pitfalls
Common mistakes when creating SNS topics with Terraform include:
- Using a
namethat already exists in your AWS account, causing conflicts. - Not specifying the AWS
providerregion, leading to resource creation in unexpected regions. - Forgetting to output or reference the topic ARN when needed for subscriptions or permissions.
Always check your AWS console for existing topics before naming.
terraform
/* Wrong: Missing provider region and duplicate name */ resource "aws_sns_topic" "dup_topic" { name = "existing-topic" } /* Right: Specify provider and unique name */ provider "aws" { region = "us-west-2" } resource "aws_sns_topic" "unique_topic" { name = "unique-topic-123" }
Quick Reference
Here is a quick summary of key properties for aws_sns_topic:
| Property | Description | Required |
|---|---|---|
| name | Unique name for the SNS topic | Yes |
| display_name | Friendly name shown in notifications | No |
| policy | JSON policy to control access | No |
| delivery_policy | JSON for delivery retry policies | No |
| tags | Key-value pairs to tag the topic | No |
Key Takeaways
Use the aws_sns_topic resource with a unique name to create an SNS topic in Terraform.
Always specify the AWS provider region to control where the topic is created.
Avoid naming conflicts by checking existing SNS topics before applying.
Output the topic ARN to use it in other resources or for permissions.
Use optional properties like display_name and tags to organize and identify topics.