QueuePolicy class

Allows you to set a policy of an SQS Queue while referencing the ARN of the queue within the policy.

> AWS will hang indefinitely when creating or updating an aws.sqs.Queue with an associated policy if Version = "2012-10-17" is not explicitly set in the policy. See below for an example of how to avoid this issue.

Example Usage

Basic Usage

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

const q = new aws.sqs.Queue("q", {name: "examplequeue"});
const test = aws.iam.getPolicyDocumentOutput({
    statements: [{
        conditions: [{
            test: "ArnEquals",
            variable: "aws:SourceArn",
            values: [example.arn],
        }],
        principals: [{
            type: "*",
            identifiers: ["*"],
        }],
        sid: "First",
        effect: "Allow",
        actions: ["sqs:SendMessage"],
        resources: [q.arn],
    }],
});
const testQueuePolicy = new aws.sqs.QueuePolicy("test", {
    queueUrl: q.id,
    policy: test.json,
});
import pulumi
import pulumi_aws as aws

q = aws.sqs.Queue("q", name="examplequeue")
test = aws.iam.get_policy_document_output(statements=[{
    "conditions": [{
        "test": "ArnEquals",
        "variable": "aws:SourceArn",
        "values": [example["arn"]],
    }],
    "principals": [{
        "type": "*",
        "identifiers": ["*"],
    }],
    "sid": "First",
    "effect": "Allow",
    "actions": ["sqs:SendMessage"],
    "resources": [q.arn],
}])
test_queue_policy = aws.sqs.QueuePolicy("test",
    queue_url=q.id,
    policy=test.json)
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;

return await Deployment.RunAsync(() =>
{
    var q = new Aws.Sqs.Queue("q", new()
    {
        Name = "examplequeue",
    });

    var test = Aws.Iam.GetPolicyDocument.Invoke(new()
    {
        Statements = new[]
        {
            new Aws.Iam.Inputs.GetPolicyDocumentStatementInputArgs
            {
                Conditions = new[]
                {
                    new Aws.Iam.Inputs.GetPolicyDocumentStatementConditionInputArgs
                    {
                        Test = "ArnEquals",
                        Variable = "aws:SourceArn",
                        Values = new[]
                        {
                            example.Arn,
                        },
                    },
                },
                Principals = new[]
                {
                    new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalInputArgs
                    {
                        Type = "*",
                        Identifiers = new[]
                        {
                            "*",
                        },
                    },
                },
                Sid = "First",
                Effect = "Allow",
                Actions = new[]
                {
                    "sqs:SendMessage",
                },
                Resources = new[]
                {
                    q.Arn,
                },
            },
        },
    });

    var testQueuePolicy = new Aws.Sqs.QueuePolicy("test", new()
    {
        QueueUrl = q.Id,
        Policy = test.Apply(getPolicyDocumentResult => getPolicyDocumentResult.Json),
    });

});
package main

import (
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/iam"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/sqs"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		q, err := sqs.NewQueue(ctx, "q", &sqs.QueueArgs{
			Name: pulumi.String("examplequeue"),
		})
		if err != nil {
			return err
		}
		test := iam.GetPolicyDocumentOutput(ctx, iam.GetPolicyDocumentOutputArgs{
			Statements: iam.GetPolicyDocumentStatementArray{
				&iam.GetPolicyDocumentStatementArgs{
					Conditions: iam.GetPolicyDocumentStatementConditionArray{
						&iam.GetPolicyDocumentStatementConditionArgs{
							Test:     pulumi.String("ArnEquals"),
							Variable: pulumi.String("aws:SourceArn"),
							Values: pulumi.StringArray{
								example.Arn,
							},
						},
					},
					Principals: iam.GetPolicyDocumentStatementPrincipalArray{
						&iam.GetPolicyDocumentStatementPrincipalArgs{
							Type: pulumi.String("*"),
							Identifiers: pulumi.StringArray{
								pulumi.String("*"),
							},
						},
					},
					Sid:    pulumi.String("First"),
					Effect: pulumi.String("Allow"),
					Actions: pulumi.StringArray{
						pulumi.String("sqs:SendMessage"),
					},
					Resources: pulumi.StringArray{
						q.Arn,
					},
				},
			},
		}, nil)
		_, err = sqs.NewQueuePolicy(ctx, "test", &sqs.QueuePolicyArgs{
			QueueUrl: q.ID().ToIDOutput().ToStringOutput(),
			Policy:   test.Json(),
		})
		if err != nil {
			return err
		}
		return nil
	})
}
pulumi {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
  }
}

data "aws_iam_getpolicydocument" "test" {
  statements {
    conditions {
      test     = "ArnEquals"
      variable = "aws:SourceArn"
      values   = [example.arn]
    }
    principals {
      type        = "*"
      identifiers = ["*"]
    }
    sid       = "First"
    effect    = "Allow"
    actions   = ["sqs:SendMessage"]
    resources = [aws_sqs_queue.q.arn]
  }
}

resource "aws_sqs_queue" "q" {
  name = "examplequeue"
}
resource "aws_sqs_queuepolicy" "test" {
  queue_url = aws_sqs_queue.q.id
  policy    = data.aws_iam_getpolicydocument.test.json
}
package generated_program;

import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.sqs.Queue;
import com.pulumi.aws.sqs.QueueArgs;
import com.pulumi.aws.iam.IamFunctions;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentArgs;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentStatementArgs;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentStatementConditionArgs;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentStatementPrincipalArgs;
import com.pulumi.aws.sqs.QueuePolicy;
import com.pulumi.aws.sqs.QueuePolicyArgs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        var q = new Queue("q", QueueArgs.builder()
            .name("examplequeue")
            .build());

        final var test = IamFunctions.getPolicyDocument(GetPolicyDocumentArgs.builder()
            .statements(GetPolicyDocumentStatementArgs.builder()
                .conditions(GetPolicyDocumentStatementConditionArgs.builder()
                    .test("ArnEquals")
                    .variable("aws:SourceArn")
                    .values(example.arn())
                    .build())
                .principals(GetPolicyDocumentStatementPrincipalArgs.builder()
                    .type("*")
                    .identifiers("*")
                    .build())
                .sid("First")
                .effect("Allow")
                .actions("sqs:SendMessage")
                .resources(q.arn())
                .build())
            .build());

        var testQueuePolicy = new QueuePolicy("testQueuePolicy", QueuePolicyArgs.builder()
            .queueUrl(q.id())
            .policy(test.applyValue(_test -> _test.json()))
            .build());

    }
}
resources:
  q:
    type: aws:sqs:Queue
    properties:
      name: examplequeue
  testQueuePolicy:
    type: aws:sqs:QueuePolicy
    name: test
    properties:
      queueUrl: ${q.id}
      policy: ${test.json}
variables:
  test:
    fn::invoke:
      function: aws:iam:getPolicyDocument
      arguments:
        statements:
          - conditions:
              - test: ArnEquals
                variable: aws:SourceArn
                values:
                  - ${example.arn}
            principals:
              - type: '*'
                identifiers:
                  - '*'
            sid: First
            effect: Allow
            actions:
              - sqs:SendMessage
            resources:
              - ${q.arn}

Timeout Problems Creating/Updating

If Version = "2012-10-17" is not explicitly set in the policy, AWS may hang, causing the AWS provider to time out. To avoid this, make sure to include Version as shown in the example below.

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

const example = new aws.s3.Bucket("example", {bucket: "brodobaggins"});
const exampleQueue = new aws.sqs.Queue("example", {name: "be-giant"});
const exampleQueuePolicy = new aws.sqs.QueuePolicy("example", {
    queueUrl: exampleQueue.id,
    policy: pulumi.jsonStringify({
        Version: "2012-10-17",
        Statement: [{
            Sid: "Cejuwdam",
            Effect: "Allow",
            Principal: {
                Service: "s3.amazonaws.com",
            },
            Action: "SQS:SendMessage",
            Resource: exampleQueue.arn,
            Condition: {
                ArnLike: {
                    "aws:SourceArn": example.arn,
                },
            },
        }],
    }),
});
import pulumi
import json
import pulumi_aws as aws

example = aws.s3.Bucket("example", bucket="brodobaggins")
example_queue = aws.sqs.Queue("example", name="be-giant")
example_queue_policy = aws.sqs.QueuePolicy("example",
    queue_url=example_queue.id,
    policy=pulumi.Output.json_dumps({
        "Version": "2012-10-17",
        "Statement": [{
            "Sid": "Cejuwdam",
            "Effect": "Allow",
            "Principal": {
                "Service": "s3.amazonaws.com",
            },
            "Action": "SQS:SendMessage",
            "Resource": example_queue.arn,
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": example.arn,
                },
            },
        }],
    }))
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Pulumi;
using Aws = Pulumi.Aws;

return await Deployment.RunAsync(() =>
{
    var example = new Aws.S3.Bucket("example", new()
    {
        BucketName = "brodobaggins",
    });

    var exampleQueue = new Aws.Sqs.Queue("example", new()
    {
        Name = "be-giant",
    });

    var exampleQueuePolicy = new Aws.Sqs.QueuePolicy("example", new()
    {
        QueueUrl = exampleQueue.Id,
        Policy = Output.JsonSerialize(Output.Create(new Dictionary<string, object?>
        {
            ["Version"] = "2012-10-17",
            ["Statement"] = new[]
            {
                new Dictionary<string, object?>
                {
                    ["Sid"] = "Cejuwdam",
                    ["Effect"] = "Allow",
                    ["Principal"] = new Dictionary<string, object?>
                    {
                        ["Service"] = "s3.amazonaws.com",
                    },
                    ["Action"] = "SQS:SendMessage",
                    ["Resource"] = exampleQueue.Arn,
                    ["Condition"] = new Dictionary<string, object?>
                    {
                        ["ArnLike"] = new Dictionary<string, object?>
                        {
                            ["aws:SourceArn"] = example.Arn,
                        },
                    },
                },
            },
        })),
    });

});
package main

import (
	"encoding/json"

	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/s3"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/sqs"
	"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func main() {
	pulumi.Run(func(ctx *pulumi.Context) error {
		example, err := s3.NewBucket(ctx, "example", &s3.BucketArgs{
			Bucket: pulumi.String("brodobaggins"),
		})
		if err != nil {
			return err
		}
		exampleQueue, err := sqs.NewQueue(ctx, "example", &sqs.QueueArgs{
			Name: pulumi.String("be-giant"),
		})
		if err != nil {
			return err
		}
		_, err = sqs.NewQueuePolicy(ctx, "example", &sqs.QueuePolicyArgs{
			QueueUrl: exampleQueue.ID().ToIDOutput().ToStringOutput(),
			Policy: pulumi.All(exampleQueue.Arn, example.Arn).ApplyT(func(_args []interface{}) (string, error) {
				exampleQueueArn := _args[0].(string)
				exampleArn := _args[1].(string)
				var _zero string
				tmpJSON0, err := json.Marshal(map[string]interface{}{
					"Version": "2012-10-17",
					"Statement": []map[string]interface{}{
						map[string]interface{}{
							"Sid":    "Cejuwdam",
							"Effect": "Allow",
							"Principal": map[string]string{
								"Service": "s3.amazonaws.com",
							},
							"Action":   "SQS:SendMessage",
							"Resource": exampleQueueArn,
							"Condition": map[string]map[string]string{
								"ArnLike": map[string]string{
									"aws:SourceArn": exampleArn,
								},
							},
						},
					},
				})
				if err != nil {
					return _zero, err
				}
				json0 := string(tmpJSON0)
				return json0, nil
			}).(pulumi.StringOutput),
		})
		if err != nil {
			return err
		}
		return nil
	})
}
pulumi {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
  }
}

resource "aws_s3_bucket" "example" {
  bucket = "brodobaggins"
}
resource "aws_sqs_queue" "example" {
  name = "be-giant"
}
resource "aws_sqs_queuepolicy" "example" {
  queue_url = aws_sqs_queue.example.id
  policy = jsonencode({
    "Version" = "2012-10-17"
    "Statement" = [{
      "Sid"    = "Cejuwdam"
      "Effect" = "Allow"
      "Principal" = {
        "Service" = "s3.amazonaws.com"
      }
      "Action"   = "SQS:SendMessage"
      "Resource" = aws_sqs_queue.example.arn
      "Condition" = {
        "ArnLike" = {
          "aws:SourceArn" = aws_s3_bucket.example.arn
        }
      }
    }]
  })
}
package generated_program;

import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.s3.Bucket;
import com.pulumi.aws.s3.BucketArgs;
import com.pulumi.aws.sqs.Queue;
import com.pulumi.aws.sqs.QueueArgs;
import com.pulumi.aws.sqs.QueuePolicy;
import com.pulumi.aws.sqs.QueuePolicyArgs;
import static com.pulumi.codegen.internal.Serialization.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String[] args) {
        Pulumi.run(App::stack);
    }

    public static void stack(Context ctx) {
        var example = new Bucket("example", BucketArgs.builder()
            .bucket("brodobaggins")
            .build());

        var exampleQueue = new Queue("exampleQueue", QueueArgs.builder()
            .name("be-giant")
            .build());

        var exampleQueuePolicy = new QueuePolicy("exampleQueuePolicy", QueuePolicyArgs.builder()
            .queueUrl(exampleQueue.id())
            .policy(Output.tuple(exampleQueue.arn(), example.arn()).applyValue(values -> {
                var exampleQueueArn = values.t1;
                var exampleArn = values.t2;
                return serializeJson(
                    jsonObject(
                        jsonProperty("Version", "2012-10-17"),
                        jsonProperty("Statement", jsonArray(jsonObject(
                            jsonProperty("Sid", "Cejuwdam"),
                            jsonProperty("Effect", "Allow"),
                            jsonProperty("Principal", jsonObject(
                                jsonProperty("Service", "s3.amazonaws.com")
                            )),
                            jsonProperty("Action", "SQS:SendMessage"),
                            jsonProperty("Resource", exampleQueueArn),
                            jsonProperty("Condition", jsonObject(
                                jsonProperty("ArnLike", jsonObject(
                                    jsonProperty("aws:SourceArn", exampleArn)
                                ))
                            ))
                        )))
                    ));
            }))
            .build());

    }
}
resources:
  example:
    type: aws:s3:Bucket
    properties:
      bucket: brodobaggins
  exampleQueue:
    type: aws:sqs:Queue
    name: example
    properties:
      name: be-giant
  exampleQueuePolicy:
    type: aws:sqs:QueuePolicy
    name: example
    properties:
      queueUrl: ${exampleQueue.id}
      policy:
        fn::toJSON:
          Version: 2012-10-17
          Statement:
            - Sid: Cejuwdam
              Effect: Allow
              Principal:
                Service: s3.amazonaws.com
              Action: SQS:SendMessage
              Resource: ${exampleQueue.arn}
              Condition:
                ArnLike:
                  aws:SourceArn: ${example.arn}

Import

Identity Schema

Required

  • queueUrl (String) URL of the SQS Queue.

Using pulumi import, import SQS Queue Policies using the queue URL. For example:

$ pulumi import aws:sqs/queuePolicy:QueuePolicy test https://queue.amazonaws.com/123456789012/myqueue

Constructors

QueuePolicy(String name, {QueuePolicyArgs? args, CustomResourceOptions? options})
Creates a new QueuePolicy. name The Pulumi resource name. args Arguments used to configure this QueuePolicy. The set of arguments for QueuePolicy. options Resource options controlling this resource's behavior.
QueuePolicy.reference(String urn)
Creates a typed reference to an existing QueuePolicy resource.

Properties

childResources → Set<Resource>
finalinherited
completionSources ↔ Map<String, IOutputCompletionSource>
latefinalinherited
hashCode → int
The hash code for this object.
no setterinherited
id ↔ Output<String>
getter/setter pairinherited
isCustom → bool
Returns whether this resource is provider-managed.
no setterinherited
isProtected → bool
Returns whether this resource is protected from deletion.
no setterinherited
isRemote → bool
Whether this resource is registered as remote.
no setterinherited
isResourceReference → bool
Whether this instance represents a resource value returned over RPC.
finalinherited
policy ↔ Output<String>
JSON policy for the SQS queue. For more information about building AWS IAM policy documents with Terraform, see the AWS IAM Policy Document Guide. Ensure that Version = "2012-10-17" is set in the policy or AWS may hang in creating the queue.
latefinal
queueUrl ↔ Output<String>
URL of the SQS Queue to which to attach the policy.
latefinal
region ↔ Output<String>
Region where this resource will be managed. Defaults to the Region set in the provider configuration.
latefinal
resourceTransforms → List<ResourceTransform>
Inherited/explicit async transforms.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
transformations → List<ResourceTransformation>
Inherited/explicit legacy transformations.
no setterinherited
urn ↔ Output<String>
latefinalinherited

Methods

failId(Object error) → void
Completes this resource ID with an error when registration fails.
inherited
failOutputs(Object error) → void
Completes all output properties with error.
inherited
failUrn(Object error) → void
Completes this resource URN with an error when registration fails.
inherited
getProvider(String moduleMember) → ProviderResource?
Returns provider for moduleMember's package, if configured.
inherited
getResourceName() → String
Returns this resource's logical name.
inherited
getResourceType() → String
Returns this resource's Pulumi type token.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
registerOutput<T>(String propertyName, {Object? decoder(Object?)?, bool isSecret = false}) → Output<T>
Registers a dynamic output property for this resource.
inherited
resolveId(String? value, {required bool isKnown}) → void
Resolves the provider-assigned ID for this resource.
inherited
resolveOutputs(Struct outputs) → void
Resolves all output properties from a monitor response payload.
inherited
resolveUrn(String value) → void
Resolves this resource's URN once assigned by the engine.
inherited
serializeProperties(Map<String, dynamic> properties) → Future<Struct>
Serializes resource properties for RPC transmission.
inherited
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

get(String name, Input<String> id, {QueuePolicyState? state, CustomResourceOptions? options}) → QueuePolicy
Gets an existing QueuePolicy resource's state with the given name and id.