Change Permission For Specific AWS S3 Folder Content in Rails

George Chkhvirkia
1 min readFeb 4, 2019

--

In certain cases we might need to change access level for content of specific folder in our S3 Bucket, and leave other folders as they are. It can be done with a few easy steps:

Step 1

Install AWS SDK for Rails:

gem 'aws-sdk-rails'

Step 2

Set AWS SDK configurations based on our credentials:

Aws.config.update(
access_key_id: ENV['key'], # e.g. 'RKIZPLO74257RMAGOEIZ'
secret_access_key: ENV['secret'], # e.g. 'q/qrzg+kt1kRB'
region: ENV['region'] # e.g. 'ca-central-1'
)

Step 3

Initialize variables for needed folder, bucket and desirable access level:

# Folder you want to change content permissions for
aws_folder = 'Uploads'
# S3 Bucket name
aws_bucket = 'some-production-ca'
# Access level, can be 'public-read', 'private', etc.
acl = 'public-read'

Step 4

Initialize new S3 Client and get the content of specified bucket:

# Init S3 Client
s3_client = Aws::S3::Client.new
# Get contents of aws_bucket
bucket_contents = s3_client.list_objects(bucket: aws_bucket).contents

Get list of names of objects(files) that are located in specified bucket’s folder:

files = bucket_contents.map{ |f| "#{f.key}" if f.key.include?(aws_folder) }.compact

Step 5 (final)

Now the part that actually changes access level. Lets loop through list of file names we’ve got and call put_object_acl method:

files.each do |obj_key|
s3_client.put_object_acl(
key: obj_key, # object(file) name
bucket: aws_bucket, # 'some-production-ca'
acl: acl # 'public-read'
)
end

Voilà!

Happy to serve you, My Lord / My Lady…

--

--