dce-dev-wizard
Version:
Wizard for managing development apps at Harvard DCE.
213 lines • 10.5 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const clear_1 = __importDefault(require("clear"));
const child_process_1 = require("child_process");
// Import helpers
const showChooser_1 = __importDefault(require("../helpers/showChooser"));
const print_1 = __importDefault(require("../helpers/print"));
const exec_1 = __importDefault(require("../helpers/exec"));
const config_1 = __importDefault(require("../helpers/config"));
const prompt_1 = __importDefault(require("../helpers/prompt"));
/**
* Connect/tunnel into a db
* @author Gabe Abrams
* @param deployment the currently selected deployment
*/
const connectToDatabase = (deployment) => __awaiter(void 0, void 0, void 0, function* () {
// Get dbName
const { dbName } = config_1.default;
// Make sure the deployment has a db
if (!dbName) {
(0, clear_1.default)();
print_1.default.title('No Database!');
console.log('');
console.log('This deployment does not have a database.');
console.log('');
print_1.default.enterToContinue();
return;
}
// Destructure
const { name, app, profile, } = deployment;
// Kill apps
(0, clear_1.default)();
print_1.default.title('Connect to database');
console.log('\nEnter sudo to cleanup existing sessions:');
(0, exec_1.default)('sudo lsof -ti tcp:27018 | xargs -r kill', true);
(0, clear_1.default)();
print_1.default.title('Connect to database');
console.log('');
// Run the connection script
const stackName = `CacclDeploy-${app}`;
// > Allow for alternate stack names
const bastionInstanceIdCommand = `aws cloudformation describe-stacks --stack-name ${stackName} --query "Stacks[].Outputs[?ExportName=='${stackName}-bastion-host-id'].OutputValue" --profile ${profile} --output text`;
console.log(`\nGetting Bastion Instance Id:\n${bastionInstanceIdCommand}\n`);
const bastionInstanceId = (0, exec_1.default)(bastionInstanceIdCommand, false).trim();
console.log(`> ${bastionInstanceId}`);
// > Endpoint/hostname of the db
const dbEndpointCommand = `aws cloudformation describe-stacks --stack-name ${stackName} --query "Stacks[].Outputs[?ExportName=='${stackName}-db-cluster-endpoint'].OutputValue" --profile ${profile} --output text`;
console.log(`\nGetting DB Endpoint:\n${dbEndpointCommand}\n`);
const dbEndpoint = (0, exec_1.default)(dbEndpointCommand, false).trim();
console.log(`> ${dbEndpoint}`);
// > Arn of the secretsmanager secret where the db master password is stored
const dbPasswordSecretCommand = `aws cloudformation describe-stacks --stack-name ${stackName} --query "Stacks[].Outputs[?ExportName=='${stackName}-db-password-secret-arn'].OutputValue" --profile ${profile} --output text`;
console.log(`\nGetting DB Password Secret:\n${dbPasswordSecretCommand}\n`);
const dbPasswordSecret = (0, exec_1.default)(dbPasswordSecretCommand, false).trim();
console.log(`> ${dbPasswordSecret}`);
// > Get DB password
const dbPasswordCommand = `aws secretsmanager get-secret-value --secret-id ${dbPasswordSecret} --query 'SecretString' --profile ${profile} --output text`;
console.log(`\nGetting DB Password:\n${dbPasswordCommand}\n`);
const dbPassword = (0, exec_1.default)(dbPasswordCommand, false).trim();
console.log(`> ${dbPassword}`);
// > Start the ssm port forwarding session
const session_args = [
'ssm',
'start-session',
'--target', bastionInstanceId,
'--document-name', 'AWS-StartPortForwardingSessionToRemoteHost',
'--parameters', `{"portNumber":["27017"],"localPortNumber":["27018"],"host":["${dbEndpoint.split(':')[0]}"]}`,
'--profile', profile,
];
console.log(`\nStarting SSM Session:\naws ${session_args.join(' ')}\n`);
(0, child_process_1.spawn)('aws', session_args, {
stdio: 'ignore',
detached: true,
});
console.log('> SSM Session started');
// Finished
console.log('\nFinished! Scroll up for errors or more details.');
// Choose an operation
const { tag } = (0, showChooser_1.default)({
question: 'Operation:',
options: [
{
description: 'Robo 3T Setup Instructions',
tag: 'R',
},
{
description: 'Studio 3T Setup Instructions',
tag: 'S',
},
{
description: 'Export Collection',
tag: 'E',
},
{
description: 'Insert Items in Collection',
tag: 'I',
},
{
description: 'Upsert Items in Collection',
tag: 'U',
},
{
description: 'Back to Main Menu',
tag: 'B',
},
],
title: 'Choose an operation:',
});
// Robo 3T
if (tag === 'R') {
(0, clear_1.default)();
print_1.default.title('Robo 3T Setup Instructions');
console.log([
'1. Open Robo 3T, create a new connection',
'2. Fill out the "Connection" tab:',
` Name = ${name}`,
` Address = localhost`,
' Port = 27018',
'3. Fill out the "Authentication" tab:',
' Check the "Perform authentication" box',
` Database = ${dbName}`,
` Username = root`,
` Password = ${dbPassword}`,
'4. Fill out the "SSL" tab:',
' Check the "Use SSL protocol" box',
' Authentication Method = Self-signed certificate',
' Check the "Advanced Options" box',
' Invalid Hostnames = Allowed',
'5. Click "Test"',
'6. If the test is successful, click "Save"',
].join('\n'));
console.log('');
print_1.default.enterToContinue();
}
// Studio 3T
if (tag === 'S') {
(0, clear_1.default)();
print_1.default.title('Studio 3T Setup Instructions');
console.log([
'1. Open Studio 3T, create a new connection',
'2. Choose "Manually configure my connection settings", then click "Next"',
`3. Set the "Connection name" to ${name}`,
'4. Fill out the "Server" tab:',
' Connection Type = Standalone',
' Address = localhost',
' Port = 27018',
'5. Fill out the "Authentication" tab:',
' Authentication Mode = Legacy',
` Username = root`,
` Password = ${dbPassword}`,
` Authentication DB = ${dbName}`,
'6. Fill out the "SSL" tab:',
' Check the "Use SSL protocol to connect" box',
' Check the "Allow invalid hostnames" box',
'5. Click "Test Connection"',
'6. If the test is successful, click "Save"',
].join('\n'));
console.log('');
yield print_1.default.enterToContinue();
}
// Export Collection
if (tag === 'E') {
(0, clear_1.default)();
print_1.default.title('Export Collection');
// Get the collection name
const collectionName = (0, prompt_1.default)('Collection Name: ');
const outFilename = `${collectionName}-${new Date().toISOString()}.json`;
console.log(`\nExporting collection to ${outFilename}\n`);
(0, exec_1.default)(`mongoexport --collection=${collectionName} --host="localhost:27018" --db=${dbName} --out="${outFilename}" --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates`, true);
console.log(`\nExported to ${outFilename}\n`);
yield print_1.default.enterToContinue();
}
// Insert Items in Collection
if (tag === 'I') {
(0, clear_1.default)();
print_1.default.title('Insert Items in Collection');
// Get the collection name
const collectionName = (0, prompt_1.default)('Collection Name: ');
console.log('\nCreate a JSON file (one entry per line), drop the file here, then press enter.');
const jsonPath = (0, prompt_1.default)('Path: ').trim();
console.log(`\nInserting items into collection "${collectionName}"\n`);
(0, exec_1.default)(`mongoimport --collection=${collectionName} --host="localhost:27018" --db=${dbName} --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates --file="${jsonPath}"`, true);
print_1.default.title('Inserted Successfully');
yield print_1.default.enterToContinue();
}
// Upsert Items in Collection
if (tag === 'U') {
(0, clear_1.default)();
print_1.default.title('Upsert Items in Collection');
// Get the collection name
const collectionName = (0, prompt_1.default)('Collection Name: ');
console.log('\nCreate a JSON file (one entry per line), drop the file here, then press enter.');
const jsonPath = (0, prompt_1.default)('Path: ').trim();
console.log(`\nUpserting items into collection "${collectionName}"\n`);
(0, exec_1.default)(`mongoimport --upsert --collection=${collectionName} --host="localhost:27018" --db=${dbName} --username=root --password=${dbPassword} --ssl --sslAllowInvalidHostnames --sslAllowInvalidCertificates --file="${jsonPath}"`, true);
print_1.default.title('Upsert Successful');
yield print_1.default.enterToContinue();
}
});
exports.default = connectToDatabase;
//# sourceMappingURL=connectToDatabase.js.map