How to Set Bucket Policy Using Boto3

Reading Time: 2 minutes

What is Boto3

Boto is a software development kit (SDK) design to enhance the use of the Python programming language by Amazon Web Services.

For more details and installation of Boto3 visit the Reference section.

Set a bucket policy

A bucket’s policy can be set by calling the put_bucket_policy method.

Example

This is the complete code to set policy.

import json
import boto3
BUCKET_NAME='harshit3bucket'
def create_bucket_policy():
	bucket_policy = {
		"Version": "2012-10-17",
		"Statement": [
			{
				"Sid": "Add Permission",
				"Effect": "Allow",
				"Principal": "*",
				"Action": ["s3:*"],
				"Resource": ["arn:aws:s3:::harshitbucket/*"]
			}
		]
	}

	policy_string = json.dumps(bucket_policy)

	s3_client().put_bucket_policy(
		Bucket=BUCKET_NAME,
		Policy=policy_string
	)

The JSON Format is used to write Bucket Policy.

How to generate Bucket policy in aws console :

Step 1 : Open the Aws Console and select the s3 option.

Step 2 : Open Bucket Policy

In the above image select the Policy generator option .

Step 3 : In the below image click on drop down option and select the S3 Bucket Policy and fill all the step in of Step 2 like principal ,Aws Service, Actions etc then click on Add Statement button.

The above images show as an example to show all field are fill.

Step 4 : After fill all details in Step 2 click on generate policy it will give policy in JSON format.

How to delete the Bucket policy

Example :

import boto3
s3_client = boto3.client("s3", region_name=AWS_REGION)
s3_client.delete_bucket_policy(Bucket=S3_BUCKET_NAME)

So this is the one of them service which is provide by Boto.There are many services which are provide by Boto3 like managing aws EC2 instances,managing IAM users, uploading and downloading files form S3 Bucket etc.

If you want to know more about boto then visit the knoldus Blog page .


Reference
Docs
https://blog.knoldus.com/introduction-to-boto3-and-its-installation/

Written by 

Harshit Gupta is a Software Consultant at knoldus Inc having few year experience in DevOps . He always eager to learn new technology and helping to others .