serverless/lib/plugins/awsCompileS3Events/awsCompileS3Events.js
Philipp Muens 67ba3f06ae Add merging of generated resources to the aws.Resources section (in service)
This way the plugin simply adds the Resources to the CloudFormation template in the
compileEvents lifecycle. The deploy plugin will use this resources to update the stack later on.
This removes the dependency between the awsCompileS3Events plugin and the deploy plugin
as the awsCompileS3Events plugin simply adds the resources to the section and forgets about it.
2016-06-09 19:08:54 +02:00

103 lines
2.8 KiB
JavaScript

'use strict';
const merge = require('lodash').merge;
class AwsCompileS3Events {
constructor(serverless) {
this.serverless = serverless;
this.hooks = {
'deploy:compileEvents': this.compileS3Events.bind(this),
};
}
compileS3Events(options) {
this.options = options;
if (!options.stage) {
throw new this.serverless.Error('Please provide a stage');
}
if (!options.region) {
throw new this.serverless.Error('Please provide a region');
}
if (!this.serverless.service.resources.aws.Resources) {
throw new this.serverless.Error(
'This plugin needs access to Resources section of the AWS CloudFormation template');
}
const bucketTemplate = `
{
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "BucketName",
"NotificationConfiguration": "NotificationConfiguration"
}
}
`;
const permissionTemplate = `
{
"Type": "AWS::Lambda::Permission",
"Properties": {
"FunctionName": "FunctionName",
"Action": "lambda:InvokeFunction",
"Principal": "s3.amazonaws.com"
}
}
`;
// iterate over all defined functions
this.serverless.service.getAllFunctions().forEach((functionName) => {
const s3BucketObject = this.serverless.service.getFunction(functionName);
// iterate over all defined buckets
s3BucketObject.events.aws.s3.forEach((bucketName) => {
// 1. create the S3 bucket with the corresponding notification
const newS3Bucket = JSON.parse(bucketTemplate);
newS3Bucket.Properties.BucketName = `${this.serverless.service.service}-${bucketName}-${
this.options.stage}-${this.options.region}`;
newS3Bucket.Properties.NotificationConfiguration = {
LambdaConfigurations: [
{
Event: 's3:ObjectCreated:*',
Function: {
'Fn::GetAtt': [
functionName,
'Arn',
],
},
},
],
};
const bucketResourceKey = bucketName.replace(/-/g, '');
const newBucketObject = {
[bucketResourceKey]: newS3Bucket,
};
// 2. create the corresponding Lambda permissions
const newPermission = JSON.parse(permissionTemplate);
newPermission.Properties.FunctionName = {
'Fn::GetAtt': [
functionName,
'Arn',
],
};
const newPermissionObject = {
[`${bucketResourceKey}Permission`]: newPermission,
};
// merge the new bucket and permission objects into the Resources section
merge(this.serverless.service.resources.aws.Resources,
newBucketObject, newPermissionObject);
});
});
}
}
module.exports = AwsCompileS3Events;