1. Answers
  2. Creating an AWS SNS Topic Policy

How do I create an AWS SNS Topic Policy?

This example demonstrates how to create an AWS SNS topic and attach a policy to it, which defines permissions and actions for accessing the topic. We’ll be defining resources such as aws_sns_topic and aws_sns_topic_policy. The policy will be a JSON document that specifies who can access the SNS topic and under which conditions. Let’s dive into the code example.

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create an SNS topic
const example = new aws.sns.Topic("example", {name: "example-topic"});
// Data source to get the current account ID
const current = aws.getCallerIdentityOutput({});
// Define the SNS topic policy as a JSON document
const snsTopicPolicy = aws.iam.getPolicyDocumentOutput({
    statements: [{
        actions: [
            "sns:Publish",
            "sns:Subscribe",
        ],
        resources: [example.arn],
        principals: [{
            identifiers: ["*"],
            type: "AWS",
        }],
        conditions: [{
            test: "StringEquals",
            variable: "aws:SourceAccount",
            values: [current.apply(current => current.accountId)],
        }],
    }],
});
// Attach the policy to the SNS topic
const exampleTopicPolicy = new aws.sns.TopicPolicy("example", {
    arn: example.arn,
    policy: snsTopicPolicy.apply(snsTopicPolicy => snsTopicPolicy.json),
});

Key Points:

  • The aws_sns_topic resource defines the SNS topic.
  • The aws_iam_policy_document data source creates a policy allowing sns:Publish and sns:Subscribe actions.
  • The aws_sns_topic_policy resource attaches the created policy to the SNS topic.
  • Use the aws_caller_identity data source to dynamically fetch the account ID.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up