forked from dougmoscrop/serverless-plugin-bootstrap
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbootstrap.js
More file actions
292 lines (247 loc) · 8.24 KB
/
bootstrap.js
File metadata and controls
292 lines (247 loc) · 8.24 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
module.exports = class BootstrapPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.provider = serverless.getProvider('aws');
this.commands = {
bootstrap: {
usage: 'Create a Change Set for a given CloudFormation template',
lifecycleEvents: [
'bootstrap'
],
options: {
execute: {
usage: 'Execute the created Change Set',
default: false
},
noCheck: {
usage: 'Skip checking changes',
default: false
}
}
}
};
this.hooks = {
'bootstrap:bootstrap': () => this.bootstrap(),
'before:deploy:deploy': () => this.bootstrap()
};
}
bootstrap() {
const custom = this.serverless.service.custom || {};
this.config = custom.bootstrap || {};
if (!this.config.file) {
throw new Error('serverless-plugin-bootstrap: must specify custom.bootstrap.file');
}
const template = this.serverless.utils.readFileSync(this.config.file);
return this.packageLocalResources(template.Resources)
.then(() => {
this.templateBody = JSON.stringify(template);
this.stackName = this.getStackName();
this.changeSetName = this.getChangeSetName();
this.params = this.getChangeSetParams();
return this.createChangeSet('UPDATE')
.catch(e => {
if (e.message.match(/does not exist/)) {
return this.createChangeSet('CREATE');
}
throw e;
})
.then(res => {
return this.getChanges(res);
})
.then(changes => {
if (changes.length) {
if (this.options.execute) {
return this.provider.request('CloudFormation', 'executeChangeSet', {
StackName: this.stackName,
ChangeSetName: this.changeSetName
});
}
if (this.options.noCheck) {
return Promise.resolve();
}
return Promise.reject(
`The stack ${this.stackName} does not match the local template. Review change set ${this.changeSetName} and either update your source code or execute the change set`
);
}
return this.provider.request('CloudFormation', 'deleteChangeSet', {
StackName: this.stackName,
ChangeSetName: this.changeSetName
});
});
});
}
getChangeSetParams() {
const capabilities = this.config.capabilities
? this.config.capabilities
: [];
const params = {
StackName: this.stackName,
ChangeSetName: this.changeSetName,
Capabilities: capabilities,
Description: 'Created by the serverless bootstrap plugin',
RoleARN: this.serverless.service.provider.cfnRole,
TemplateBody: this.templateBody,
};
if (this.config.parameters) {
params.Parameters = this.config.parameters;
}
return params;
}
getStackName() {
if (this.config.stack) {
return this.config.stack;
}
const fileName = path.basename(this.config.file, path.extname(this.config.file));
const serviceName = this.serverless.service.service;
return `${serviceName}-${fileName}`;
}
getChangeSetName() {
const parameters = this.config.parameters;
const md5 = crypto.createHash('md5')
.update(this.templateBody)
.update(parameters ? JSON.stringify(parameters) : '')
.digest('hex');
return `serverless-bootstrap-${md5}`;
}
getChanges(res) {
if (res.Status === 'FAILED') {
if (res.StatusReason.match(/The submitted information didn't contain changes/)) {
return [];
}
throw new Error(`createChangeSet FAILED: ${res.StatusReason}`);
}
if (res.Status === 'CREATE_COMPLETE') {
return res.Changes.filter(change => {
if (change.Type === 'Resource') {
const resourceChange = change.ResourceChange;
// CloudFormation Nested Stacks seem to always show up as 'Modify'
// but when nothing has actually changed, Details is an array of Targets with no Name
if (resourceChange.Action === 'Modify' && resourceChange.ResourceType === 'AWS::CloudFormation::Stack') {
return resourceChange.Details.some(detail => detail.Target.Name);
}
}
return true;
});
}
throw new Error(`Expected res.Status to be CREATE_COMPLETE but got ${res.Status}`);
}
createChangeSet(changeSetType) {
const params = Object.assign({}, this.params, { ChangeSetType: changeSetType });
return this.provider.request('CloudFormation', 'createChangeSet', params)
.then(res => {
const credentials = this.provider.getCredentials();
const cf = new this.provider.sdk.CloudFormation(credentials);
return cf.waitFor('changeSetCreateComplete', {
StackName: this.stackName,
ChangeSetName: this.changeSetName,
NextToken: res.NextToken
})
.promise()
.catch(e => {
if (e.message.match(/Resource is not in the state/)) {
// TODO: NextToken support for large (> 1MB) changes
return this.provider.request('CloudFormation', 'describeChangeSet', {
StackName: this.stackName,
ChangeSetName: this.changeSetName
});
}
throw e;
});
});
}
packageLocalResources(resources = {}) {
const bucket = `${this.config.stack}-resources`;
const uploads = Object.keys(resources).reduce((memo, logicalId) => {
const resource = resources[logicalId];
const properties = resource.Properties;
if (resource.Type === 'AWS::CloudFormation::Stack') {
const url = properties.TemplateURL;
if (!this.isRemote(url)) {
memo.push(() => {
return this.uploadResource(bucket, url)
.then(newURL => {
properties.TemplateURL = newURL;
});
});
}
}
return memo;
}, []);
if (uploads.length > 0) {
return this.ensureResourceBucketExists(bucket)
.then(() => {
return Promise.all(uploads.map(upload => upload()));
});
}
return Promise.resolve();
}
isRemote(url) {
return url && url.indexOf('https://') === 0;
}
// TODO: Even for remote resources, we should attach metadata about the template md5
// to detect if it has changed
ensureResourceBucketExists(bucket) {
return this.provider.request('S3', 'headBucket', {
Bucket: bucket
})
.then(() => false)
.catch(e => {
if (e.statusCode === 404) {
return true;
}
throw new Error('AWS Request Error determining if bootstrap resources bucket exists');
})
.then(create => {
if (create) {
return this.provider.request('S3', 'createBucket', {
Bucket: bucket
});
}
});
}
uploadResource(bucket, localFile) {
const dir = path.dirname(this.config.file);
const file = path.join(process.cwd(), dir, localFile);
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(file);
const hash = crypto.createHash('md5');
rs.pipe(hash)
.on('error', reject)
.on('finish', () => {
resolve(hash.read().toString('hex'));
});
})
.then(hash => {
const name = path.basename(file, path.extname(file));
const key = `${name}-${hash}`;
return this.provider.request('S3', 'headObject', {
Bucket: bucket,
Key: key
})
.then(() => false)
.catch(e => {
if (e.statusCode === 404) {
return true;
}
throw new Error('AWS Request Error determining if bootstrap resource already uploaded');
})
.then(upload => {
if (upload) {
return this.provider.request('S3', 'upload', {
Bucket: bucket,
Key: key,
Body: fs.createReadStream(file)
})
}
})
.then(() => {
return `https://s3.amazonaws.com/${bucket}/${key}`;
});
});
}
};