-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
index.js
110 lines (101 loc) · 3.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
'use strict';
const path = require('path');
const createZipFile = require('../../../utils/fs/createZipFile');
function addCustomResourceToService(resourceName, iamRoleStatements) {
let FunctionName;
let Handler;
let customResourceFunctionLogicalId;
const Statement = iamRoleStatements;
const customResourcesRoleLogicalId = this.provider.naming.getCustomResourcesRoleLogicalId();
const srcDirPath = path.join(__dirname, 'resources');
const destDirPath = path.join(
this.serverless.config.servicePath,
'.serverless',
this.provider.naming.getCustomResourcesArtifactDirectoryName()
);
const zipFilePath = `${destDirPath}.zip`;
this.serverless.utils.writeFileDir(zipFilePath);
if (resourceName === 's3') {
FunctionName = `${this.serverless.service.service}-${
this.options.stage
}-${this.provider.naming.getCustomResourceS3HandlerFunctionName()}`;
Handler = 's3/handler.handler';
customResourceFunctionLogicalId = this.provider.naming.getCustomResourceS3HandlerFunctionLogicalId();
}
return createZipFile(srcDirPath, zipFilePath).then(outputFilePath => {
let S3Bucket = {
Ref: this.provider.naming.getDeploymentBucketLogicalId(),
};
if (this.serverless.service.package.deploymentBucket) {
S3Bucket = this.serverless.service.package.deploymentBucket;
}
const s3Folder = this.serverless.service.package.artifactDirectoryName;
const s3FileName = outputFilePath.split(path.sep).pop();
const S3Key = `${s3Folder}/${s3FileName}`;
const customResourceRole = {
[customResourcesRoleLogicalId]: {
Type: 'AWS::IAM::Role',
Properties: {
AssumeRolePolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
Service: ['lambda.amazonaws.com'],
},
Action: ['sts:AssumeRole'],
},
],
},
Policies: [
{
PolicyName: {
'Fn::Join': [
'-',
[
this.provider.getStage(),
this.provider.serverless.service.service,
'custom-resources-lambda',
],
],
},
PolicyDocument: {
Version: '2012-10-17',
Statement,
},
},
],
},
},
};
const customResourceFunction = {
[customResourceFunctionLogicalId]: {
Type: 'AWS::Lambda::Function',
Properties: {
Code: {
S3Bucket,
S3Key,
},
FunctionName,
Handler,
MemorySize: 1024,
Role: {
'Fn::GetAtt': [customResourcesRoleLogicalId, 'Arn'],
},
Runtime: 'nodejs10.x',
Timeout: 6,
},
DependsOn: [customResourcesRoleLogicalId],
},
};
Object.assign(
this.serverless.service.provider.compiledCloudFormationTemplate.Resources,
customResourceFunction,
customResourceRole
);
});
}
module.exports = {
addCustomResourceToService,
};