Creates an SNS topic and attaches a custom IAM policy to it, allowing various SNS actions based on specific conditions.

Terraform Template

data "aws_iam_policy_document" "sns_topic_policy" {
  policy_id = "__default_policy_ID"

  statement {
    actions = ["SNS:Subscribe", "SNS:SetTopicAttributes", "SNS:RemovePermission", "SNS:Receive", "SNS:Publish", "SNS:ListSubscriptionsByTopic", "SNS:GetTopicAttributes", "SNS:DeleteTopic", "SNS:AddPermission"]

    condition {
      test = "StringEquals"
      values = ["var.account-id"]
      variable = "AWS:SourceOwner"
    }
    effect = "Allow"

    principals {
      identifiers = [*]
      type = "AWS"
    }
    resources = [aws_sns_topic.test.arn]
    sid = "__default_statement_ID"
  }
}

resource "aws_sns_topic" "test" {
  name = "my-topic-with-policy"
}

resource "aws_sns_topic_policy" "default" {
  arn = aws_sns_topic.test.arn
  policy = data.aws_iam_policy_document.sns_topic_policy.json
}