我尝试使用Ruby SDK设置存储桶策略,如下所示:
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!
但它似乎并没有储蓄。我查看了ruby documentation,但不清楚如何做到这一点。如果可能的话,我也希望能够打印出桶的当前政策。
答案 0 :(得分:3)
看看以下示例。这允许您设置策略并检索策略(如果需要,请记住更改存储桶名称并添加凭据/更改区域。)
您可能希望细化策略本身以将其限制为某个对象(文件夹和文件都是对象)。请记住,如果您有一个S3布局,例如my-bucket-name /文件夹/文件,并且您希望仅限制到该文件夹,那么它将是arn:aws:s3:::my-bucket-name/folder/*
作为ARN。
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/*\"}]}"