This repository was archived by the owner on Jun 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
422 lines (352 loc) · 13.2 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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
var _ = require('lodash');
var execSync = require('sync-exec');
var customCommands = require('./customCommands');
function mergeOptions(opts) {
if (this && this._options && opts) {
_.merge(this._options, opts);
}
}
function makeJsonSafeForCommandLine(json) {
return (
'\'' +
json
.replace(/'/g, '\'"\'"\'')
.replace(/(\$OBSCURED_KEY_[\d]+)/g, '\'"$1"\'') +
'\''
);
}
// For more info, see: http://docs.aws.amazon.com/cli/latest/userguide/shorthand-syntax.html
function _optsToFlags(opts) {
return !_.isPlainObject(opts) ? (opts || []) :
_.reduce(
opts,
function(result, val, key) {
if (val != null) {
result.push(key + (val ? ' ' + val : ''));
}
return result;
},
[]
);
}
var keysForPasswordPrivateExporting = ['HaproxyStatsPassword', 'MysqlRootPassword', 'GangliaPassword'];
var keysToConsiderForCertPrivateExporting = ['SshKey', 'SshPrivateKey', 'Certificate', 'PrivateKey', 'Chain'];
var valPrefixRequiredForCertPrivateExporting = /^[\r\n]*-----BEGIN (RSA PRIVATE KEY|CERTIFICATE)-----[\r\n]/;
var valSuffixRequiredForCertPrivateExporting = /[\r\n]-----END (RSA PRIVATE KEY|CERTIFICATE)-----[\r\n]*$/;
var keysForDoubleEncodingAndDecoding = ['CustomJson', 'AssumeRolePolicyDocument', 'PolicyDocument'];
function _prepareInput(input) {
var preppedInput = {
json: '',
exports: ''
};
var rawFlagsStr = '';
var json = '';
var exports = [];
if (typeof input === 'string' && input) {
rawFlagsStr = input;
}
else if (input) {
json =
JSON.stringify(
input,
function(key, val) {
var exportIndex = exports.length + 1;
// Handle passwords and certificates slightly differently by
// exporting their values to a temporary environment variable and then
// referencing that variable within the JSON string during the
// command's execution. This helps provide a better attempt at
// security/privacy for consumers by not visibly displaying their
// passwords/certificates on the terminal screen!
if (
typeof val === 'string' && val &&
(
_.contains(keysForPasswordPrivateExporting, key) ||
(
_.contains(keysToConsiderForCertPrivateExporting, key) &&
valPrefixRequiredForCertPrivateExporting.test(val) &&
valSuffixRequiredForCertPrivateExporting.test(val)
)
)
) {
exports.push([
'OBSCURED_KEY_' + exportIndex,
val
]);
return '$OBSCURED_KEY_' + exportIndex;
}
// Double-encode some objects into a JSON stringified-string (as the API demands)
if (_.contains(keysForDoubleEncodingAndDecoding, key) && _.isPlainObject(val)) {
return JSON.stringify(val);
}
// Convert Filters to final format:
// [{ Name: 'Name1', Values: ['Val1', ...] }, ...]
if (key === 'Filters' && _.isPlainObject(val)) {
var isFilterHash = _.every(val, function(v, k) { return typeof k === 'string' && !!k && v != null && (_.isArray(v) || !_.isObject(v)); });
if (isFilterHash) {
return _.reduce(
val,
function(result, v, k) {
result.push({
Name: k,
Values: _.map((_.isArray(v) ? v : [v]), String) // Force to an Array of Strings
});
return result;
},
[]
);
}
}
// Convert PolicyAttributes to final format:
// [{ AttributeName: 'Name1', AttributeValue: 'Val1' }, ...]
if (key === 'PolicyAttributes' && _.isPlainObject(val)) {
var isAttrHash = _.every(val, function(v, k) { return typeof k === 'string' && typeof v !== 'undefined' && !!k && v != null; });
if (isAttrHash) {
return _.reduce(
val,
function(result, v, k) {
result.push({
AttributeName: k,
AttributeValue: '' + v // AttributeValue must be a String
});
return result;
},
[]
);
}
}
// Convert Tags to final format:
// [{ Key: 'Tag1', Value: 'TagVal1'}, ...]
if (key === 'Tags' || key === 'AdditionalAttributes') {
if (_.isArray(val)) {
// From:
// [['Tag1', 'TagVal1'], ['Tag2', 'TagVal2']]
var isArrArr = _.every(val, function(arr) { return _.isArray(arr) && arr.length === 2 && _.every(arr, function(s) { return typeof s === 'string' && !!s; }); });
if (isArrArr) {
return _.map(val, function(arr) {
return {
Key: arr[0],
Value: arr[1]
};
});
}
// Or from:
// [{ Tag1: 'TagVal1' }, { Tag2: 'TagVal2' }]
// But NOT from:
// << the correct final format, mentioned above >>
var isArrHash = _.every(val, function(h) { return _.isPlainObject(h) && _.keys(h).length === 1 && _.every(h, function(v, k) { return typeof k === 'string' && !!k && typeof v === 'string' && !!v; }); });
if (isArrHash) {
return _.flatten(
_.map(
val,
function(h) {
return _.map(
h,
function(v, k) {
return {
Key: k,
Value: v
};
}
);
}
)
);
}
}
else if (_.isPlainObject(val)) {
// Or from:
// { Tag1: 'TagVal1', Tag2: 'TagVal2' }
var isHash = _.every(val, function(v, k) { return typeof k === 'string' && typeof v === 'string' && !!k && !!v; });
if (isHash) {
return _.reduce(
val,
function(result, v, k) {
result.push({
Key: k,
Value: v
});
return result;
},
[]
);
}
}
}
// Other just return the original
return val;
}
);
}
if (exports.length > 0) {
preppedInput.exports =
_.map(exports, function(pair) {
return 'export ' + pair[0] + '=\'' + JSON.stringify(pair[1]).slice(1, -1) + '\'';
})
.join('; ');
}
preppedInput.json = json ? '--cli-input-json ' + makeJsonSafeForCommandLine(json) : rawFlagsStr;
return preppedInput;
}
function _parseOutput(json) {
return (
!json ?
null :
JSON.parse(
json || 'null',
function(key, val) {
// Double-decode some objects from a JSON stringified-string (as the API provides)
if (_.contains(keysForDoubleEncodingAndDecoding, key) && _.isString(val)) {
return JSON.parse(val);
}
return val;
}
)
);
}
function _awsExec(rawCmd, customOptions, exports) {
customOptions = customOptions || {};
var cmd = 'aws ' + rawCmd;
if (customOptions.cmdTrace === true) {
// IMPORTANT: For security/privacy reasons, we do NOT normally show the custom shell exports
//console.warn('[TRACE] Exports preamble:\n ' + exports + '\n[/TRACE]\n');
console.warn('[TRACE] Raw AWS command:\n ' + cmd + '\n[/TRACE]\n');
}
// If we have any `exports`, we must add surrounding parentheses to create a sub-shell or else the
// variable references don't seem to resolve correctly
var result = execSync((exports ? '(' + exports + '; ' : '') + cmd + (exports ? ')' : ''));
if (result.status !== 0) {
throw new Error('Failed to execute AWS command:\n ' + cmd + '\n\n' + (result.stderr || result.stdout));
}
if (customOptions.cmdTrace === true) {
console.warn('[TRACE] Raw AWS response:\n' + result.stdout + '\n[/TRACE]\n');
}
return _parseOutput(result.stdout);
}
var AwsCli =
module.exports =
function AwsCli(opts) {
if (!(this instanceof AwsCli)) {
return new AwsCli(opts);
}
this._options = opts || {};
};
AwsCli.prototype.o = AwsCli.prototype.options = mergeOptions;
var AwsService =
AwsCli.prototype.s =
AwsCli.prototype.serv =
AwsCli.prototype.service =
function AwsService(name, opts, cli) {
if (!(this instanceof AwsService)) {
if (this instanceof AwsCli) {
return new AwsService(name, opts, this);
}
return new AwsService(name, opts);
}
this._cli = cli || new AwsCli();
this._name = name;
this._options = opts || {};
// OpsWorks currently only has a service endpoint in region "us-east-1", so force that
if (this._name === 'opsworks') {
if (!this._options.flags) {
this._options.flags = {};
}
this._options.flags['--region'] = 'us-east-1';
}
};
AwsService.prototype.o = AwsService.prototype.options = mergeOptions;
var AwsCommand =
AwsService.prototype.c =
AwsService.prototype.cmd =
AwsService.prototype.command =
function AwsCommand(cmd, input, overrideOpts) {
var service = this;
if (!(service instanceof AwsService)) {
throw new Error('Trying to execute AwsCommand without a parent AwsService');
}
input = input || {};
overrideOpts = overrideOpts || {};
// Internal-only hack
var printOnly = arguments[2] === true;
var _exec = !printOnly ? _awsExec : function(rawCmd, options /* , exports */) {
console.warn('[NOT EXECUTING]\n Command: ' + rawCmd + '\n Options: ' + JSON.stringify(options) + '\n');
};
var serviceName = service._name;
var mergedFlags = _.merge(
{},
service._cli._options.flags,
service._options.flags,
overrideOpts.flags
);
var mergedOptions = _.merge(
_.omit(service._cli._options, 'flags'),
_.omit(service._options, 'flags'),
_.omit(overrideOpts, 'flags')
);
var _execWrapper = function(realCmd, realInput, realOverrideOpts) {
var finalFlags = _.merge({}, mergedFlags, (realOverrideOpts || {}).flags);
var finalOptions = _.merge({}, mergedOptions, _.omit(realOverrideOpts || {}, 'flags'));
var preppedRealInput = _prepareInput(realInput || {});
var cliFlagKeys = _.keys(service._cli._options.flags);
var serviceFlagKeys = _.difference(_.keys(service._options.flags), cliFlagKeys);
var otherFlagKeys = _.difference(_.keys(finalFlags), cliFlagKeys, serviceFlagKeys);
var cliFlagsStr = _optsToFlags(_.pick(finalFlags, cliFlagKeys)).join(' ');
var serviceFlagsStr = _optsToFlags(_.pick(finalFlags, serviceFlagKeys)).join(' ');
var otherFlagsStr = _optsToFlags(_.pick(finalFlags, otherFlagKeys)).join(' ');
var globalAndServiceBaseCommandStr =
(cliFlagsStr ? cliFlagsStr + ' ' : '') +
serviceName + ' ' +
(serviceFlagsStr ? serviceFlagsStr + ' ' : '') +
(otherFlagsStr ? otherFlagsStr + ' ' : '');
return _exec(
globalAndServiceBaseCommandStr + realCmd + ' ' + preppedRealInput.json,
finalOptions,
preppedRealInput.exports
);
};
// If there is a custom command mapping, delegate to that function instead, e.g. "associate-network-acl"
if (
customCommands.hasOwnProperty(serviceName) &&
customCommands[serviceName] != null &&
customCommands[serviceName].hasOwnProperty(cmd) &&
typeof customCommands[serviceName][cmd] === 'function'
) {
return customCommands[serviceName][cmd](input, _execWrapper);
}
return _execWrapper(cmd, input);
};
AwsCommand.printOnly = function(cmd, input) {
if (!(this instanceof AwsService)) {
throw new Error('Trying to execute AwsCommand without a parent AwsService');
}
var _printOnly = true;
return this.command(cmd, input, _printOnly);
};
AwsCli.prototype.run =
function AwsCliRun(service, cmd, input) {
if (!(this instanceof AwsCli)) {
throw new Error('Trying to execute AwsCommand without an ancestor AwsCli');
}
return this.service(service).command(cmd, input);
};
AwsCli.prototype.version =
function AwsCliGetVersion() {
if (!(this instanceof AwsCli)) {
throw new Error('Trying to execute AwsCommand without an ancestor AwsCli');
}
// Redirect stderr to stdout... stderr seems to get lost sometimes with the execSync module
var cmd = 'aws --version 2>&1';
var result = execSync(cmd);
if (result.status !== 0) {
throw new Error('Failed to execute AWS command:\n ' + cmd + '\n\n' + (result.stderr || result.stdout));
}
// Example output (to stderr, normally):
// aws-cli/1.9.17 Python/2.7.10 Darwin/15.2.0 botocore/1.3.17
var versionFullStr = (result.stdout || '').replace(/^\s+|\s+$/g, '');
var versionMatchingRegex = /^aws(?:-cli)?\/([\d]+\.[\d]+\.[^\s]+)(?:\s.*)?$/i;
var versionMatch = versionFullStr.match(versionMatchingRegex);
var versionShortStr = (versionMatch && versionMatch.length > 1) ? versionMatch[1] : null;
if (!versionShortStr) {
throw new Error('Failed to determine AWS CLI version!\nFull version string was: ' + versionFullStr);
}
return versionShortStr;
};