This complex template sets up a cross-account and cross-region subscription from an SNS topic to an SQS queue, including IAM policies and roles for permissions.

Terraform Template

variable "sns" {
  default = "[object Object]"
}

variable "sqs" {
  default = "[object Object]"
}

data "aws_iam_policy_document" "sns-topic-policy" {
  policy_id = "__default_policy_ID"

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

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

    principals {
      identifiers = [*]
      type = "AWS"
    }
    resources = ["arn:aws:sns:${var.sns["region"]}:${var.sns["account-id"]}:${var.sns["name"]}"]
    sid = "__default_statement_ID"
  }

  statement {
    actions = ["SNS:Subscribe", "SNS:Receive"]

    condition {
      test = "StringLike"
      values = ["arn:aws:sqs:${var.sqs["region"]}:${var.sqs["account-id"]}:${var.sqs["name"]}"]
      variable = "SNS:Endpoint"
    }
    effect = "Allow"

    principals {
      identifiers = [*]
      type = "AWS"
    }
    resources = ["arn:aws:sns:${var.sns["region"]}:${var.sns["account-id"]}:${var.sns["name"]}"]
    sid = "__console_sub_0"
  }
}

data "aws_iam_policy_document" "sqs-queue-policy" {
  policy_id = "arn:aws:sqs:${var.sqs["region"]}:${var.sqs["account-id"]}:${var.sqs["name"]}/SQSDefaultPolicy"

  statement {
    actions = ["SQS:SendMessage"]

    condition {
      test = "ArnEquals"
      values = ["arn:aws:sns:${var.sns["region"]}:${var.sns["account-id"]}:${var.sns["name"]}"]
      variable = "aws:SourceArn"
    }
    effect = "Allow"

    principals {
      identifiers = [*]
      type = "AWS"
    }
    resources = ["arn:aws:sqs:${var.sqs["region"]}:${var.sqs["account-id"]}:${var.sqs["name"]}"]
    sid = "example-sns-topic"
  }
}

resource "aws_sns_topic" "sns-topic" {
  display_name = "var.sns["display_name"]"
  name = "var.sns["name"]"
  policy = data.aws_iam_policy_document.sns-topic-policy.json
  provider = "aws.sns"
}

resource "aws_sns_topic_subscription" "sns-topic" {
  endpoint = aws_sqs_queue.sqs-queue.arn
  protocol = "sqs"
  provider = "aws.sns2sqs"
  topic_arn = aws_sns_topic.sns-topic.arn
}

resource "aws_sqs_queue" "sqs-queue" {
  name = "var.sqs["name"]"
  policy = data.aws_iam_policy_document.sqs-queue-policy.json
  provider = "aws.sqs"
}