如何创建具有公共读取访问权限的存储桶?

Kla*_*aas 6 amazon-s3 serverless

我想对我的存储桶中 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
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试对文件使用 url 时,它返回访问被拒绝。我必须在 aws-s3 Web 界面中手动设置每个文件的公共读取权限。

我究竟做错了什么?

Mil*_*mak 6

CorsConfiguration您需要为其附加一个存储桶策略,而不是在存储桶上使用。请尝试以下操作:

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: "*"

Run Code Online (Sandbox Code Playgroud)


max*_*x_i 6

接受的答案对我不起作用。CloudFormation 无法更新资源并出现以下错误:

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)

资源定义中似乎缺少通配符。对我有用的完整片段:

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: '*'
Run Code Online (Sandbox Code Playgroud)