BucketPolicy class

Attaches a policy to an S3 bucket resource.

> Policies can be attached to both S3 general purpose buckets and S3 directory buckets.

Example Usage

Basic Usage

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

const example = new aws.s3.Bucket("example", {bucket: "my-tf-test-bucket"});
const allowAccessFromAnotherAccount = aws.iam.getPolicyDocumentOutput({
    statements: [{
        principals: [{
            type: "AWS",
            identifiers: ["123456789012"],
        }],
        actions: [
            "s3:GetObject",
            "s3:ListBucket",
        ],
        resources: [
            example.arn,
            pulumi.interpolate`${example.arn}/*`,
        ],
    }],
});
const allowAccessFromAnotherAccountBucketPolicy = new aws.s3.BucketPolicy("allow_access_from_another_account", {
    bucket: example.id,
    policy: allowAccessFromAnotherAccount.json,
});
import pulumi
import pulumi_aws as aws

example = aws.s3.Bucket("example", bucket="my-tf-test-bucket")
allow_access_from_another_account = aws.iam.get_policy_document_output(statements=[{
    "principals": [{
        "type": "AWS",
        "identifiers": ["123456789012"],
    }],
    "actions": [
        "s3:GetObject",
        "s3:ListBucket",
    ],
    "resources": [
        example.arn,
        example.arn.apply(lambda arn: f"{arn}/*"),
    ],
}])
allow_access_from_another_account_bucket_policy = aws.s3.BucketPolicy("allow_access_from_another_account",
    bucket=example.id,
    policy=allow_access_from_another_account.json)
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;

return await Deployment.RunAsync(() =>
{
    var example = new Aws.S3.Bucket("example", new()
    {
        BucketName = "my-tf-test-bucket",
    });

    var allowAccessFromAnotherAccount = Aws.Iam.GetPolicyDocument.Invoke(new()
    {
        Statements = new[]
        {
            new Aws.Iam.Inputs.GetPolicyDocumentStatementInputArgs
            {
                Principals = new[]
                {
                    new Aws.Iam.Inputs.GetPolicyDocumentStatementPrincipalInputArgs
                    {
                        Type = "AWS",
                        Identifiers = new[]
                        {
                            "123456789012",
                        },
                    },
                },
                Actions = new[]
                {
                    "s3:GetObject",
                    "s3:ListBucket",
                },
                Resources = new[]
                {
                    example.Arn,
                    $"{example.Arn}/*",
                },
            },
        },
    });

    var allowAccessFromAnotherAccountBucketPolicy = new Aws.S3.BucketPolicy("allow_access_from_another_account", new()
    {
        Bucket = example.Id,
        Policy = allowAccessFromAnotherAccount.Apply(getPolicyDocumentResult => getPolicyDocumentResult.Json),
    });

});
package main

import (
	"fmt"

	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/iam"
	"github.com/pulumi/pulumi-aws/sdk/v7/go/aws/s3"
	"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("my-tf-test-bucket"),
		})
		if err != nil {
			return err
		}
		allowAccessFromAnotherAccount := iam.GetPolicyDocumentOutput(ctx, iam.GetPolicyDocumentOutputArgs{
			Statements: iam.GetPolicyDocumentStatementArray{
				&iam.GetPolicyDocumentStatementArgs{
					Principals: iam.GetPolicyDocumentStatementPrincipalArray{
						&iam.GetPolicyDocumentStatementPrincipalArgs{
							Type: pulumi.String("AWS"),
							Identifiers: pulumi.StringArray{
								pulumi.String("123456789012"),
							},
						},
					},
					Actions: pulumi.StringArray{
						pulumi.String("s3:GetObject"),
						pulumi.String("s3:ListBucket"),
					},
					Resources: pulumi.StringArray{
						example.Arn,
						example.Arn.ApplyT(func(arn string) (string, error) {
							return fmt.Sprintf("%v/*", arn), nil
						}).(pulumi.StringOutput),
					},
				},
			},
		}, nil)
		_, err = s3.NewBucketPolicy(ctx, "allow_access_from_another_account", &s3.BucketPolicyArgs{
			Bucket: example.ID().ToIDOutput().ToStringOutput(),
			Policy: allowAccessFromAnotherAccount.Json(),
		})
		if err != nil {
			return err
		}
		return nil
	})
}
pulumi {
  required_providers {
    aws = {
      source = "pulumi/aws"
    }
  }
}

data "aws_iam_getpolicydocument" "allowAccessFromAnotherAccount" {
  statements {
    principals {
      type        = "AWS"
      identifiers = ["123456789012"]
    }
    actions   = ["s3:GetObject", "s3:ListBucket"]
    resources = [aws_s3_bucket.example.arn, "${aws_s3_bucket.example.arn}/*"]
  }
}

resource "aws_s3_bucket" "example" {
  bucket = "my-tf-test-bucket"
}
resource "aws_s3_bucketpolicy" "allow_access_from_another_account" {
  bucket = aws_s3_bucket.example.id
  policy = data.aws_iam_getpolicydocument.allowAccessFromAnotherAccount.json
}
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.iam.IamFunctions;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentArgs;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentStatementArgs;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentStatementPrincipalArgs;
import com.pulumi.aws.s3.BucketPolicy;
import com.pulumi.aws.s3.BucketPolicyArgs;
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("my-tf-test-bucket")
            .build());

        final var allowAccessFromAnotherAccount = IamFunctions.getPolicyDocument(GetPolicyDocumentArgs.builder()
            .statements(GetPolicyDocumentStatementArgs.builder()
                .principals(GetPolicyDocumentStatementPrincipalArgs.builder()
                    .type("AWS")
                    .identifiers("123456789012")
                    .build())
                .actions(
                    "s3:GetObject",
                    "s3:ListBucket")
                .resources(
                    example.arn(),
                    example.arn().applyValue(_arn -> String.format("%s/*", _arn)))
                .build())
            .build());

        var allowAccessFromAnotherAccountBucketPolicy = new BucketPolicy("allowAccessFromAnotherAccountBucketPolicy", BucketPolicyArgs.builder()
            .bucket(example.id())
            .policy(allowAccessFromAnotherAccount.applyValue(_allowAccessFromAnotherAccount -> _allowAccessFromAnotherAccount.json()))
            .build());

    }
}
resources:
  example:
    type: aws:s3:Bucket
    properties:
      bucket: my-tf-test-bucket
  allowAccessFromAnotherAccountBucketPolicy:
    type: aws:s3:BucketPolicy
    name: allow_access_from_another_account
    properties:
      bucket: ${example.id}
      policy: ${allowAccessFromAnotherAccount.json}
variables:
  allowAccessFromAnotherAccount:
    fn::invoke:
      function: aws:iam:getPolicyDocument
      arguments:
        statements:
          - principals:
              - type: AWS
                identifiers:
                  - '123456789012'
            actions:
              - s3:GetObject
              - s3:ListBucket
            resources:
              - ${example.arn}
              - ${example.arn}/*

> Only one aws.s3.BucketPolicy resource should be defined per S3 bucket. Defining multiple aws.s3.BucketPolicy resources with different Pulumi names but the same bucket value may result in unexpected policy overwrites. Each resource uses the PutBucketPolicy API, which replaces the entire existing policy without error or warning. Because Pulumi treats each resource independently, the policy applied last will silently override any previously applied policy.

Import

Identity Schema

Required

  • bucket (String) Name of the S3 bucket.

Optional

  • accountId (String) AWS Account where this resource is managed.
  • region (String) Region where this resource is managed.

Using pulumi import, import S3 bucket policies using the bucket name. For example:

$ pulumi import aws:s3/bucketPolicy:BucketPolicy example my-tf-test-bucket

Constructors

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

Properties

bucket ↔ Output<String>
Name of the bucket to which to apply the policy.
latefinal
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>
Text of the policy. Although this is a bucket policy rather than an IAM policy, the aws.iam.getPolicyDocument data source may be used, so long as it specifies a principal. For more information about building AWS IAM policy documents, see the AWS IAM Policy Document Guide. Note: Bucket policies are limited to 20 KB in size.
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, {BucketPolicyState? state, CustomResourceOptions? options}) → BucketPolicy
Gets an existing BucketPolicy resource's state with the given name and id.