Ped*_*nso 10 amazon-s3 aws-cloudformation aws-lambda 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:
- "*"
Run Code Online (Sandbox Code Playgroud)
不确定是否可能,或者serverless.yml在部署过程中如何利用上传默认文件(如果还没有).
没有正式的AWS CloudFormation资源可以管理(添加/删除)Bucket中的单个S3对象,但是您可以使用自定义资源创建一个使用Lambda函数来使用AWS SDK for NodeJS 调用PUT Object/ DELETE ObjectAPI的资源.
这是一个完整的CloudFormation模板示例:
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}"
Run Code Online (Sandbox Code Playgroud)
您应该也能够在serverless.yml配置文件中使用这些资源,但我不确定无服务器如何与CloudFormation资源/参数集成.
| 归档时间: |
|
| 查看次数: |
10255 次 |
| 最近记录: |