我们如何使用serverless.yml创建AWS S3存储桶并向其添加文件?

时间:2017-01-10 15:21:12

标签: amazon-s3 aws-lambda amazon-cloudformation serverless-framework

我想知道是否可以利用serverless.yml创建存储桶并在无服务器框架的部署过程中向其添加特定文件。

到目前为止,我已经能够添加创建存储桶的S3资源,但不知道如何添加特定文件。

resources:
  Resources:
    UploadBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:custom.s3.bucket}
        AccessControl: Private
        CorsConfiguration:
          CorsRules:
          - AllowedMethods:
            - GET
            - PUT
            - POST
            - HEAD
            AllowedOrigins:
            - "*"
            AllowedHeaders:
            - "*"

不确定是否可行,或者在部署过程中如何利用serverless.yml上传默认文件,如果它还没有。

3 个答案:

答案 0 :(得分:6)

没有正式的AWS CloudFormation资源可以管理(添加/删除)Bucket中的单个S3对象,但您可以使用Custom Resource创建一个使用Lambda函数调用PUT Object的资源。 } / DELETE Object使用AWS SDK for NodeJS的API。

以下是CloudFormation模板的完整示例:

Launch Stack

Description: Create an S3 Object using a Custom Resource.
Parameters:
  BucketName:
    Description: S3 Bucket Name (must not already exist)
    Type: String
  Key:
    Description: S3 Object Key
    Type: String
  Body:
    Description: S3 Object Body
    Type: String
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref BucketName
  S3Object:
    Type: Custom::S3Object
    Properties:
      ServiceToken: !GetAtt S3ObjectFunction.Arn
      Bucket: !Ref Bucket
      Key: !Ref Key
      Body: !Ref Body
  S3ObjectFunction:
    Type: AWS::Lambda::Function
    Properties:
      Description: S3 Object Custom Resource
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        ZipFile: !Sub |
          var response = require('cfn-response');
          var AWS = require('aws-sdk');
          var s3 = new AWS.S3();
          exports.handler = function(event, context) {
            var respond = (e) => response.send(event, context, e ? response.FAILED : response.SUCCESS, e ? e : {});
            var params = event.ResourceProperties;
            delete params.ServiceToken;
            if (event.RequestType == 'Create' || event.RequestType == 'Update') {
              s3.putObject(params).promise()
                .then((data)=>respond())
                .catch((e)=>respond(e));
            } else if (event.RequestType == 'Delete') {
              delete params.Body;
              s3.deleteObject(params).promise()
                .then((data)=>respond())
                .catch((e)=>respond(e));
            } else {
              respond({Error: 'Invalid request type'});
            }
          };
      Timeout: 30
      Runtime: nodejs4.3
  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal: {Service: [lambda.amazonaws.com]}
          Action: ['sts:AssumeRole']
      Path: /
      ManagedPolicyArns:
      - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
      - PolicyName: S3Policy
        PolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - 's3:PutObject'
                - 'S3:DeleteObject'
              Resource: !Sub "arn:aws:s3:::${BucketName}/${Key}"

您应该能够在serverless.yml配置文件中使用这些资源,但我并不确定无服务器如何与CloudFormation资源/参数集成。

答案 1 :(得分:0)

您是否研究过serverless-s3-sync插件。它允许您将文件夹从本地计算机上载到S3,作为部署的一部分。

plugins:
  - serverless-s3-sync
custom:
  s3Sync:
    - bucketName: ${self:custom.s3.bucket} # required
      bucketPrefix: assets/ # optional
      localDir: dist/assets # required

答案 2 :(得分:0)

如果这样做是为了部署网站,则可以使用serverless-finch,如果尚不存在,它将自动为您创建存储桶。