問題描述
如何創建具有公共讀取訪問權限的存儲桶? (How to create a bucket with Public Read Access?)
我想對我的 Bucket 中 serverless.yml 文件的“public”文件夾中的所有項目啟用公共讀取訪問權限。
目前這是我用來聲明的定義代碼我的桶。它從無服務器堆棧示例之一複制和粘貼。
Resources:
AttachmentsBucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: PublicRead
# Set the CORS policy
BucketName: range‑picker‑bucket‑${self:custom.stage}
CorsConfiguration:
CorsRules:
‑
AllowedOrigins:
‑ '*'
AllowedHeaders:
‑ '*'
AllowedMethods:
‑ GET
‑ PUT
‑ POST
‑ DELETE
‑ HEAD
MaxAge: 3000
# Print out the name of the bucket that is created
Outputs:
AttachmentsBucketName:
Value:
Ref: AttachmentsBucket
現在,當我嘗試對文件使用 url 時,它返回訪問被拒絕。我必須在 aws‑s3 Web 界面中手動設置每個文件的公共讀取權限。
我做錯了什麼?
參考解法
方法 1:
Instead of using CorsConfiguration
on the bucket, you need to attach a bucket policy to it. Try the following:
Resources:
AttachmentsBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: range‑picker‑bucket‑${self:custom.stage}
AttachmentsBucketAllowPublicReadPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref AttachmentsBucket
PolicyDocument:
Version: "2012‑10‑17"
Statement:
‑ Effect: Allow
Action:
‑ "s3:GetObject"
Resource:
‑ !Join ['/', [!Ref AttachmentsBucket, 'public']]
Principal: "*"
方法 2:
Accepted answer didn't work for me. CloudFormation failed to update the resource with the error:
Action does not apply to any resource(s) in statement (Service: Amazon S3; Status Code: 400; Error Code: MalformedPolicy; Request ID: <...>; S3 Extended Request ID: <...>; Proxy: null)
It appears the wildcard was missing in the resource definition. Full snippet that worked for me:
PublicBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: 'public‑bucket‑name'
PublicBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref PublicBucket
PolicyDocument:
Version: '2012‑10‑17'
Statement:
‑ Effect: Allow
Action:
‑ 's3:GetObject'
Resource:
‑ !Join ['/', [!GetAtt [PublicBucket, Arn], '*']]
Principal: '*'
方法 3:
As the others have said, you need to implement a Bucket Policy such as this one:
{
"Version": "2012‑10‑17",
"Statement": [
{
"Sid": "PublicReadForGetBucketObjects",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::{NAME_OF_YOUR_BUCKET_HERE}/*"
}
]
}
This can be done in the AWS console by selecting the Bucket, then Permissions, then Bucket Policy. Looks like @Milan C. is indicating how to declare this in a serverless.yml file.
(by Klaas、Milan Cermak、Max Ivanov、CSSian)