-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
index.ts
178 lines (160 loc) · 5.55 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
/* eslint-disable no-console */
import { execSync } from 'child_process';
import { AwsSdkCall } from '../aws-custom-resource';
/**
* Flattens a nested object
*
* @param object the object to be flattened
* @returns a flat object with path as keys
*/
export function flatten(object: object): { [key: string]: string } {
return Object.assign(
{},
...function _flatten(child: any, path: string[] = []): any {
return [].concat(...Object.keys(child)
.map(key =>
typeof child[key] === 'object' && child[key] !== null
? _flatten(child[key], path.concat([key]))
: ({ [path.concat([key]).join('.')]: child[key] }),
));
}(object),
);
}
/**
* Decodes encoded true/false values
*/
function decodeBooleans(object: object) {
return JSON.parse(JSON.stringify(object), (_k, v) => {
switch (v) {
case 'TRUE:BOOLEAN':
return true;
case 'FALSE:BOOLEAN':
return false;
default:
return v;
}
});
}
/**
* Filters the keys of an object.
*/
function filterKeys(object: object, pred: (key: string) => boolean) {
return Object.entries(object)
.reduce(
(acc, [k, v]) => pred(k)
? { ...acc, [k]: v }
: acc,
{},
);
}
let latestSdkInstalled = false;
export function forceSdkInstallation() {
latestSdkInstalled = false;
}
/**
* Installs latest AWS SDK v2
*/
function installLatestSdk(): void {
console.log('Installing latest AWS SDK v2');
// Both HOME and --prefix are needed here because /tmp is the only writable location
execSync('HOME=/tmp npm install aws-sdk@2 --production --no-package-lock --no-save --prefix /tmp');
latestSdkInstalled = true;
}
/* eslint-disable @typescript-eslint/no-require-imports, import/no-extraneous-dependencies */
export async function handler(event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context) {
try {
let AWS: any;
if (!latestSdkInstalled && event.ResourceProperties.InstallLatestAwsSdk === 'true') {
try {
installLatestSdk();
AWS = require('/tmp/node_modules/aws-sdk');
} catch (e) {
console.log(`Failed to install latest AWS SDK v2: ${e}`);
AWS = require('aws-sdk'); // Fallback to pre-installed version
}
} else if (latestSdkInstalled) {
AWS = require('/tmp/node_modules/aws-sdk');
} else {
AWS = require('aws-sdk');
}
console.log(JSON.stringify(event));
console.log('AWS SDK VERSION: ' + AWS.VERSION);
// Default physical resource id
let physicalResourceId: string;
switch (event.RequestType) {
case 'Create':
physicalResourceId = event.ResourceProperties.Create?.physicalResourceId?.id ??
event.ResourceProperties.Update?.physicalResourceId?.id ??
event.ResourceProperties.Delete?.physicalResourceId?.id ??
event.LogicalResourceId;
break;
case 'Update':
case 'Delete':
physicalResourceId = event.ResourceProperties[event.RequestType]?.physicalResourceId?.id ?? event.PhysicalResourceId;
break;
}
let flatData: { [key: string]: string } = {};
let data: { [key: string]: string } = {};
const call: AwsSdkCall | undefined = event.ResourceProperties[event.RequestType];
if (call) {
const awsService = new (AWS as any)[call.service]({
apiVersion: call.apiVersion,
region: call.region,
});
try {
const response = await awsService[call.action](call.parameters && decodeBooleans(call.parameters)).promise();
flatData = {
apiVersion: awsService.config.apiVersion, // For test purposes: check if apiVersion was correctly passed.
region: awsService.config.region, // For test purposes: check if region was correctly passed.
...flatten(response),
};
data = call.outputPath
? filterKeys(flatData, k => k.startsWith(call.outputPath!))
: flatData;
} catch (e) {
if (!call.ignoreErrorCodesMatching || !new RegExp(call.ignoreErrorCodesMatching).test(e.code)) {
throw e;
}
}
if (call.physicalResourceId?.responsePath) {
physicalResourceId = flatData[call.physicalResourceId.responsePath];
}
}
await respond('SUCCESS', 'OK', physicalResourceId, data);
} catch (e) {
console.log(e);
await respond('FAILED', e.message || 'Internal Error', context.logStreamName, {});
}
function respond(responseStatus: string, reason: string, physicalResourceId: string, data: any) {
const responseBody = JSON.stringify({
Status: responseStatus,
Reason: reason,
PhysicalResourceId: physicalResourceId,
StackId: event.StackId,
RequestId: event.RequestId,
LogicalResourceId: event.LogicalResourceId,
NoEcho: false,
Data: data,
});
console.log('Responding', responseBody);
// eslint-disable-next-line @typescript-eslint/no-require-imports
const parsedUrl = require('url').parse(event.ResponseURL);
const requestOptions = {
hostname: parsedUrl.hostname,
path: parsedUrl.path,
method: 'PUT',
headers: { 'content-type': '', 'content-length': responseBody.length },
};
return new Promise((resolve, reject) => {
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const request = require('https').request(requestOptions, resolve);
request.on('error', reject);
request.write(responseBody);
request.end();
} catch (e) {
reject(e);
}
});
}
}