This Python example shows you how to:
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.
To set up and run this example, you must first complete this task:
The example below shows how to:
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)
The example below shows how to:
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)
The example below shows how to:
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')