How to apply s3 bucket policy using Python

This post explains how to apply and get S3 bucket policy using Python. A bucket policy is a resource-based policy that you can use to grant access permissions to your bucket and the objects in it.

Prerequisite

To run the python script for getting bucket policy from your local machine you need to have Boto3 credential set up, refer Setting up boto3 credentials for configuring Boto3 credentials.

Apply S3 Bucket Policy Using Python

AWS Boto3 SDK provides put_bucket_policy api to put policy on a specified S3 bucket. For performing this operation the calling identity must have PutBucketPolicy permissions on the bucket.

Python Code to Get Policy Applied to S3 Bucket

Let's apply below sample policy to S3 bucket. This policy provides GetObject permissions to IAM role with ARN IAM_ROLE_ARN on bucket with ARN BUCKET_ARN.

   
  import json
  import boto3
  
  s3_client = boto3.client("s3")
  
  bucket_name = "test-bucket-12344321"
  
  bucket_policy = {
      "Id":
      "sid1",
      "Version":
      "2012-10-17",
      "Statement": [{
          "Sid": "Sid1",
          "Action": ["s3:GetObject"],
          "Effect": "Allow",
          "Resource": ["BUCKET_ARN/*"],
          "Principal": {
              "AWS": ["IAM_ROLE_ARN"]
          }
      }]
  }
  
  response = s3_client.put_bucket_policy(Bucket=bucket_name,
                                          Policy=json.dumps(bucket_policy))
  
  print(response)
    
   

Get S3 Bucket Policy Using Python

AWS Boto3 SDK provides get_bucket_policy api to retrieve the policy applied to a specified bucket. For performing this operation the calling identity must have GetBucketPolicy permissions on the bucket.

   
  import boto3

  s3_client = boto3.client("s3")
  
  bucket_name = "test-bucket-12344321"
  
  response = s3_client.get_bucket_policy(Bucket=bucket_name)
  
  print(response)
    
   

Follow US on Twitter:

Category: AWS

Python For Beginners