S3: make a public folder private again?

前端 未结 12 2100
北恋
北恋 2021-01-30 20:16

How do you make an AWS S3 public folder private again?

I was testing out some staging data, so I made the entire folder public within a bucket. I\'d like to restrict it

12条回答
  •  情书的邮戳
    2021-01-30 20:27

    From what I understand, the 'Make public' option in the managment console recursively adds a public grant for every object 'in' the directory. You can see this by right-clicking on one file, then click on 'Properties'. You then need to click on 'Permissions' and there should be a line:

     Grantee:  Everyone  [x] open/download  [] view permissions   [] edit permission.
    

    If you upload a new file within this directory it won't have this public access set and therefore be private.

    You need to remove public read permission one by one, either manually if you only have a few keys or by using a script.

    I wrote a small script in Python with the 'boto' module to recursively remove the 'public read' attribute of all keys in a S3 folder:

    #!/usr/bin/env python
    #remove public read right for all keys within a directory
    
    #usage: remove_public.py bucketName folderName
    
    import sys
    import boto3
    
    BUCKET = sys.argv[1]
    PATH = sys.argv[2]
    s3client = boto3.client("s3")
    paginator = s3client.get_paginator('list_objects_v2')
    page_iterator = paginator.paginate(Bucket=BUCKET, Prefix=PATH)
    for page in page_iterator:
        keys = page['Contents']
        for k in keys:
            response = s3client.put_object_acl(
                            ACL='private',
                            Bucket=BUCKET,
                            Key=k['Key']
                        )
    

    I tested it in a folder with (only) 2 objects and it worked. If you have lots of keys it may take some time to complete and a parallel approach might be necessary.

提交回复
热议问题