forked from udondan/aws-cloudformation-custom-resource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
323 lines (279 loc) · 7.4 KB
/
index.ts
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { Callback, Context } from 'aws-lambda';
import AWS = require('aws-sdk');
import https = require('https');
import URL = require('url');
/**
* The event passed to the Lambda handler
*/
export interface LambdaEvent {
[key: string]: any;
}
/**
* The event passed through the promises.
*/
export interface Event extends LambdaEvent {
/**
* Adds values to the response returned to CloudFormation
*/
addResponseValue: (key: string, value: any) => void;
/**
* Set the physical ID of the resource
*/
setPhysicalResourceId: (value: any) => void;
}
/**
* Function signature
*/
export type func = (event: Event) => Promise<Event | AWS.AWSError>;
/**
* Custom CloudFormation resource helper
*/
export class CustomResource {
/**
* Stores functions executed when resource creation is requested
*/
createFunctions: func[] = [];
/**
* Stores functions executed when resource update is requested
*/
updateFunctions: func[] = [];
/**
* Stores functions executed when resource deletion is requested
*/
deleteFunctions: func[] = [];
/**
* The context passed to the Lambda handler
*/
context: Context;
/**
* The callback function passed to the Lambda handler
*/
callback: Callback;
/**
* Stores values returned to CloudFormation
*/
ResponseData: {
[key: string]: any;
} = {};
/**
* Stores values physical ID of the resource
*/
PhysicalResourceId?: string;
/**
* Logger class
*/
logger: Logger;
constructor(context: Context, callback: Callback, logger?: Logger) {
this.context = context;
this.callback = callback;
this.logger = logger || new StandardLogger();
}
/**
* Adds a function to the CREATE queue
*/
onCreate(func: func): this {
this.createFunctions.push(func);
return this;
}
/**
* Adds a function to the UPDATE queue
*/
onUpdate(func: func): this {
this.updateFunctions.push(func);
return this;
}
/**
* Adds a function to the DELETE queue
*/
onDelete(func: func): this {
this.deleteFunctions.push(func);
return this;
}
/**
* Handles the Lambda event
*/
handle(event: LambdaEvent): this {
const lambdaEvent = event;
const self = this;
if (typeof lambdaEvent.ResponseURL === 'undefined') {
throw new Error('ResponseURL missing');
}
this.logger.debug(`REQUEST RECEIVED:\n${JSON.stringify(lambdaEvent)}`);
this.timeout(lambdaEvent);
event.addResponseValue = (key: string, value: any) => {
self.ResponseData[key] = value;
};
event.setPhysicalResourceId = (value: string) => {
self.PhysicalResourceId = value;
};
try {
let queue: func[];
if (lambdaEvent.RequestType == 'Create') queue = this.createFunctions;
else if (lambdaEvent.RequestType == 'Update')
queue = this.updateFunctions;
else if (lambdaEvent.RequestType == 'Delete')
queue = this.deleteFunctions;
else {
this.sendResponse(
lambdaEvent,
'FAILED',
`Unexpected request type: ${lambdaEvent.RequestType}`
);
return this;
}
let result = queue.reduce(
(current: Promise<Event | AWS.AWSError> | func, next: func) => {
return (current as Promise<Event>).then((value: Event) => {
return next(value);
});
},
Promise.resolve(event as Event)
);
result
.then(function (event: Event | AWS.AWSError) {
self.logger.debug(event);
self.sendResponse(
lambdaEvent,
'SUCCESS',
`${lambdaEvent.RequestType} completed successfully`
);
})
.catch(function (err: AWS.AWSError) {
self.logger.error(err, err.stack);
self.sendResponse(lambdaEvent, 'FAILED', err.message || err.code);
});
} catch (err) {
this.sendResponse(lambdaEvent, 'FAILED', err.message || err.code);
}
return this;
}
/**
* Sends CloudFormation response just before the Lambda times out
*/
timeout(event: LambdaEvent) {
const self = this;
const handler = () => {
self.logger.error('Timeout FAILURE!');
new Promise(() =>
self.sendResponse(event, 'FAILED', 'Function timed out')
).then(() => self.callback(new Error('Function timed out')));
};
setTimeout(handler, this.context.getRemainingTimeInMillis() - 1000);
}
/**
* Sends CloudFormation response
*/
sendResponse(
event: LambdaEvent,
responseStatus: string,
responseData: string
) {
const self = this;
this.logger.debug(
`Sending response ${responseStatus}:\n${JSON.stringify(responseData)}`
);
const data = this.ResponseData;
data['Message'] = responseData;
const body = JSON.stringify({
Status: responseStatus,
Reason: `${responseData} | Full error in CloudWatch ${this.context.logStreamName}`,
PhysicalResourceId:
self.PhysicalResourceId || event.PhysicalResourceId || event.ResourceProperties.Name,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
Data: data,
});
this.logger.debug('RESPONSE BODY:\n', body);
const url = URL.parse(event.ResponseURL);
const options = {
hostname: url.hostname,
port: 443,
path: url.path,
method: 'PUT',
headers: {
'content-type': '',
'content-length': body.length,
},
};
this.logger.info('SENDING RESPONSE...\n');
const request = https.request(options, function (response: any) {
self.logger.debug(`STATUS: ${response.statusCode}`);
self.logger.debug(`HEADERS: ${JSON.stringify(response.headers)}`);
self.context.done();
});
request.on('error', function (error: Error) {
self.logger.error(`sendResponse Error: ${error}`);
self.context.done();
});
request.write(body);
request.end();
}
}
/**
* Logger class
*/
export interface Logger {
log(message: any, ...optionalParams: any[]): void;
info(message: any, ...optionalParams: any[]): void;
debug(message: any, ...optionalParams: any[]): void;
warn(message: any, ...optionalParams: any[]): void;
error(message: any, ...optionalParams: any[]): void;
}
/**
* LogLevels supported by the logger
*/
export const enum LogLevel {
ERROR,
WARN,
INFO,
DEBUG,
}
/**
* Standard logger class
*/
export class StandardLogger {
/**
* The log level
*
* @default LogLevel.WARN
*/
level: LogLevel;
constructor(level?: LogLevel) {
this.level = level || LogLevel.WARN;
}
/**
* Logs message with level ERROR
*/
error(message: any, ...optionalParams: any[]) {
if (this.level < LogLevel.ERROR) return;
console.error(message, ...optionalParams);
}
/**
* Logs message with level WARN
*/
warn(message: any, ...optionalParams: any[]) {
if (this.level < LogLevel.WARN) return;
console.warn(message, ...optionalParams);
}
/**
* Logs message with level INFO
*/
info(message: any, ...optionalParams: any[]) {
if (this.level < LogLevel.INFO) return;
console.info(message, ...optionalParams);
}
/**
* Logs message with level DEBUG
*/
debug(message: any, ...optionalParams: any[]) {
if (this.level < LogLevel.DEBUG) return;
console.debug(message, ...optionalParams);
}
/**
* Alias for info
*/
log(message: any, ...optionalParams: any[]) {
this.info(message, ...optionalParams);
}
}