How to make s3 bucket public in python

2019-09-19 04:48发布

问题:

I have an already created bucket in amazon s3. I want to make its content publicly available without any authentication. I have tried from documents of boto

To set a canned ACL for a bucket, use the set_acl method of the Bucket object. The argument passed to this method must be one of the four permissable canned policies named in the list CannedACLStrings contained in acl.py. For example, to make a bucket readable by anyone:

b.set_acl('public-read')

It is not working. I still cant access my files publicly. However setting acl to public-read for individual files is working.

I want to make it public from python as I don't have access to s3 console.

I want to make whole bucket publicly readable.

My code is

    conn = boto.connect_s3(
        aws_access_key_id = access_key,
        aws_secret_access_key = secret_key,
        host = 's3.amazonaws.com',
        #is_secure=False,               # uncomment if you are not using ssl
        calling_format = boto.s3.connection.OrdinaryCallingFormat(),
        )
bucket = conn.get_bucket('media_library')
bucket.set_acl('public-read')

回答1:

You will need to create a Bucket Policy, which defines permissions on the bucket as a whole.

See 'Bucket Policy' in: Managing Access to S3 Resources (Access Policy Options)

You can do this via boto in Python with put_bucket_policy():

put_bucket_policy(**kwargs)

Replaces a policy on a bucket. If the bucket already has a policy, the one in this request completely replaces it.

Request Syntax

response = client.put_bucket_policy(Bucket='string', Policy='string')

See Bucket Policy Examples to find a suitable policy.

Here is a policy that makes the whole bucket publicly readable (just insert your own bucket name):

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