8

Trying to figure out a way to set ACLs on objects in an S3 bucket using Boto3. Input should be the S3 bucket name and change the ACLs for all the objects to read only by public

Vzzarr
  • 4,600
  • 2
  • 43
  • 80
Ramu
  • 111
  • 1
  • 2
  • 7

4 Answers4

12

From the boto3 docs

To change the ACL of a single object, first get the Object instance and then change the ACL. This next example does both:

(boto3
 .session
 .Session(region_name=<region_name>)
 .resource('s3')
 .Object(<bucket_name>, <key>)
 .Acl()
 .put(ACL='public-read'))

To change the ACL of a bucket, assuming you already have the bucket instance:

bucket.Acl().put(ACL='public-read')
alejandrodnm
  • 5,410
  • 3
  • 26
  • 28
3

In my case I had to specify the ACL for new Objects being written in S3 so based on https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Object.put

import boto3

s3 = boto3.resource("s3") 
s3.Object(my_bucket_name, my_key_path).put(Body=my_body, ACL=my_acl)

where my_acl can be one of:

'private'|'public-read'|'public-read-write'|'authenticated-read'|'aws-exec-read'|'bucket-owner-read'|'bucket-owner-full-control'
Vzzarr
  • 4,600
  • 2
  • 43
  • 80
1

You can copy_object() the object to itself, while setting the ACL.

So, the source will be the same as the destination, but set the ACL to your desired value.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
  • Can you please provide a code example of how to do this? – Will Nilges Oct 16 '22 at 10:59
  • 1
    @rkj Just use the `copy_object()` command as you normally would, but specify the same Bucket and Key for both the source and the destination. Then, specify the ACL as part of the copy. You can append `extra_args = { 'ACL': 'public-read'}` to the copy. See an example: [boto3 copy vs copy_object regarding file permission ACL in s3](https://stackoverflow.com/a/50993333/174777) – John Rotenstein Oct 16 '22 at 21:32
0

Another way to do it with the body is:

aws s3api put-bucket-acl --bucket bucket_name --access-control-policy file://grant.json

grant.json file:

{
    "Grants": [
            {
            "Grantee": {
                "ID": "CANONICAL_ID_TO_GRANT",
                "Type": "CanonicalUser"
            },
            "Permission": "WRITE"
            },
            {
            "Grantee": {
                "ID": "CANONICAL_ID_TO_GRANT",
                "Type": "CanonicalUser"
            },
            "Permission": "READ"
            }
        ],
        "Owner": {
            "DisplayName": "example_owner",
            "ID": "CANONICAL_ID_OWNER"
        }
}
Luigi Lopez
  • 1,037
  • 10
  • 23