Working with Amazon S3 Bucket Policies

This Python example shows you how to:

  • Get the bucket policy of an Amazon S3 bucket.
  • Add or update the bucket policy of an Amazon S3 bucket.
  • Delete the bucket policy of an Amazon S3 bucket.

The Scenario

In this example, Python code is used to get, set, or delete a bucket policy on an Amazon S3 bucket. The code uses the AWS SDK for Python to configure policy for a selected Amazon S3 bucket using these methods of the Amazon S3 client class:

For more information about bucket policies for Amazon S3 buckets, see Using Bucket Policies and User Policies in the Amazon Simple Storage Service Developer Guide.

All the example code for the Amazon Web Services (AWS) SDK for Python is available here on GitHub.

Prerequisite Tasks

To set up and run this example, you must first complete this task:

  • Configure your AWS credentials, as described in Quickstart.

Get the Current Bucket Policy

The example below shows how to:

Example

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Call to S3 to retrieve the policy for the given bucket
result = s3.get_bucket_policy(Bucket='my-bucket')
print(result)

Set a Simple Bucket Policy

The example below shows how to:

Example

import boto3
import json

# Create an S3 client
s3 = boto3.client('s3')

bucket_name = 'my-bucket'

# Create the bucket policy
bucket_policy = {
    'Version': '2012-10-17',
    'Statement': [{
        'Sid': 'AddPerm',
        'Effect': 'Allow',
        'Principal': '*',
        'Action': ['s3:GetObject'],
        'Resource': "arn:aws:s3:::%s/*" % bucket_name
    }]
}

# Convert the policy to a JSON string
bucket_policy = json.dumps(bucket_policy)

# Set the new policy on the given bucket
s3.put_bucket_policy(Bucket=bucket_name, Policy=bucket_policy)

Delete a Bucket Policy

The example below shows how to:

Example

import boto3

# Create an S3 client
s3 = boto3.client('s3')

# Call S3 to delete the policy for the given bucket
s3.delete_bucket_policy(Bucket='my-bucket')