I'm trying to set a bucket policy using the Ruby SDK like this:
s3 = Aws::S3::Resource.new(region:'us-east-1')
obj = s3.bucket('my-bucket-name')
policy = AWS::S3::Policy.new
policy.allow(
:actions => [:get_object],
:resources => [obj],
:principals => :any)
obj.policy = policy
obj.save!
But it doesn't seem to be saving. I've looked through the ruby documentation but it's not clear how to do this. I'd also like to be able to print out the current policies for the bucket if possible.
Have a look at the following example. This allows you to set a policy and retrieve a policy (remember to change the bucket name and add credentials / change region if need be).
You may want to fine-grain the policy itself to restrict it to some object (folders and files are both objects). Remember that if you have an S3 layout such as my-bucket-name/folder/file and you wish to only restrict to that folder then it would be arn:aws:s3:::my-bucket-name/folder/*
as the ARN.
Documentation for setting and getting policy.
require 'aws-sdk'
require 'json'
s3 = Aws::S3::Client.new(region: 'us-east-1')
policy = {
"Version":"2012-10-17",
"Statement":[
{
"Sid":"AddPerm",
"Effect":"Allow",
"Principal": "*",
"Action":["s3:GetObject"],
"Resource":["arn:aws:s3:::my-bucket-name/*"]
}
]
}
s3.put_bucket_policy({
bucket: "my-bucket-name",
policy: policy.to_json
})
=> #<struct Aws::EmptyStructure>
resp = s3.get_bucket_policy({
bucket: "my-bucket-name",
})
resp.policy.read
=> "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"AddPerm\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::my-bucket-name/*\"}]}"
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments