Open In App

Create Bucket Policy in AWS S3 Bucket with Python

Bucket policy of s3 bucket means permission and action which can be applied on the particular bucket. AWS S3 has an optional policy that can be used to restrict or grant access to an S3 bucket resource.  It is important to note that bucket policies are defined in JSON format.

For creating a bucket policy in python we will follow the below steps:



import json
import boto3

       

Example:



bucket_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "AddPerm",
                "Effect": "Allow",
                "Principal": "*",
                "Action": ["s3:*"],
                "Resource": ["arn:aws:s3:::gfgbucket/*"]
            }
        ]
    }

Step 3: The third step will need to convert the bucket policy string in JSON.

json.dumps(bucket_policy)

Step 4:  The fourth step will be for putting bucket policy to the bucket we need to call put_bucket_policy() function .this function will take the first parameter the bucket name and the second parameter will be the policy string.

put_bucket_policy(Bucket,policy)

Step 5: The last step will be to go to AWS->S3->Bucket->Permission->Bucket policy and verify.

            

Complete code:




import json
import boto3
s3_client=boto3.client('s3')
BUCKET_NAME='gfgbucket'
def create_bucket_policy():
    bucket_policy = {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "AddPerm",
                "Effect": "Allow",
                "Principal": "*",
                "Action": ["s3:*"],
                "Resource": ["arn:aws:s3:::gfgbucket/*"]
            }
        ]
    }
  
    policy_string = json.dumps(bucket_policy)
  
     s3_client().put_bucket_policy(
        Bucket=BUCKET_NAME,
        Policy=policy_string
    )

Output:


Article Tags :