rds_ssm_connect 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -0
  3. package/connect.js +115 -0
  4. package/package.json +13 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Iaroslav Pyrogov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # AWS Environment Selector and Command Executor
2
+
3
+ This Node.js application allows you to select an AWS environment and execute various AWS commands within that environment. The environments are read from your AWS configuration file, and the application uses the `aws-vault` tool to securely manage your AWS credentials.
4
+
5
+ ## Prerequisites
6
+
7
+ Before running this application, make sure you have the following installed:
8
+
9
+ - Node.js: You can download it from the [official website](https://nodejs.org/).
10
+ - `aws-vault` tool: You can install it following the instructions on the [official GitHub page](https://github.com/99designs/aws-vault).
11
+ - AWS CLI: You can install it following the instructions on the [official AWS page](https://aws.amazon.com/cli/).
12
+
13
+ Also, ensure that your AWS configuration file (`~/.aws/config`) is properly set up with the environments you want to use.
14
+
15
+ ## Installation
16
+
17
+ 1. Clone the repository or download the source code.
18
+ 2. Navigate to the project directory.
19
+ 3. Install the necessary Node.js dependencies by running:
20
+
21
+ ```bash
22
+ npm install
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ 1. Run the application. It will read your AWS configuration file and prompt you to select an environment.
28
+
29
+ ```bash
30
+ node connect.js
31
+ ```
32
+
33
+ 2. Select the environment you want to use. The application will then execute a series of AWS commands within that environment.
34
+
35
+ ## Requirements
36
+
37
+ This application requires the following Node.js modules:
38
+
39
+ - `child_process`: For spawning child processes to execute AWS commands.
40
+ - `inquirer`: For prompting the user to select an environment.
41
+ - `fs`: For reading the AWS configuration file.
42
+ - `os`: For getting the user's home directory.
43
+ - `path`: For working with file paths.
44
+
45
+ You can install these modules by running:
46
+
47
+ ```bash
48
+ npm install child_process inquirer fs os path
49
+ ```
50
+
51
+ ## How It Works
52
+
53
+ The application first reads the AWS configuration file and extracts the environments from it. It then prompts the user to select an environment.
54
+
55
+ After the user selects an environment, the application executes a series of AWS commands within that environment using `aws-vault`. These commands include:
56
+
57
+ - Describing SSM parameters to get the name of the parameter containing the RDS password.
58
+ - Getting the value of the RDS password parameter.
59
+ - Describing EC2 instances to get the ID of the bastion instance.
60
+ - Describing RDS DB clusters to get the endpoint of the RDS cluster.
61
+ - Starting an AWS SSM session to forward a local port to the RDS cluster.
62
+
63
+ The application logs the output of each command and any errors that occur.
package/connect.js ADDED
@@ -0,0 +1,115 @@
1
+ // Import necessary modules
2
+ import { spawn } from 'child_process'; // For spawning child processes
3
+ import inquirer from 'inquirer'; // For prompting the user for input
4
+ import fs from 'fs'; // For reading files
5
+ import os from 'os'; // For getting the user's home directory
6
+ import path from 'path'; // For working with file paths
7
+
8
+ // Get the path to the AWS config file
9
+ const awsConfigPath = path.join(os.homedir(), '.aws', 'config');
10
+
11
+ // Read the contents of the AWS config file
12
+ const awsConfig = fs.readFileSync(awsConfigPath, 'utf-8');
13
+
14
+ // Extract environments from AWS config file
15
+ const ENVS = awsConfig
16
+ .split('\n')
17
+ .filter(line => line.startsWith('[') && line.endsWith(']'))
18
+ .map(line => line.slice(1, -1))
19
+ .map(line => line.replace('profile ', ''));
20
+
21
+ // Prompt the user to select an environment
22
+ inquirer
23
+ .prompt([
24
+ {
25
+ type: 'list',
26
+ name: 'ENV',
27
+ message: 'Please select the environment:',
28
+ choices: ENVS,
29
+ },
30
+ ])
31
+ .then((answers) => {
32
+ const ENV = answers.ENV; // Get the selected environment from the user's answers
33
+ console.log(`You selected: ${ENV}`);
34
+
35
+ // Set up the commands to run inside the aws-vault environment
36
+ const awsVaultExecCommand = ['aws-vault', 'exec', ENV, '--'];
37
+ const ssmDescribeCommand = 'aws ssm describe-parameters --region us-east-2 --query \'Parameters[?ends_with(Name, `/rds/rds-aurora-password`)].Name\' --output text | head -n 1';
38
+
39
+ // Run the commands inside aws-vault environment
40
+ const ssmDescribeProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmDescribeCommand}`]);
41
+
42
+ // Get the name of the parameter containing the RDS password
43
+ ssmDescribeProcess.stdout.on('data', (data) => {
44
+ const PARAM_NAME = data.toString().trim();
45
+
46
+ // Get the RDS credentials
47
+ const ssmGetCommand = `aws ssm get-parameter --region us-east-2 --name '${PARAM_NAME}' --with-decryption --query Parameter.Value --output text`;
48
+ const ssmGetProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmGetCommand}`]);
49
+
50
+ // Parse the JSON output of the ssm get-parameter command to get the RDS credentials
51
+ ssmGetProcess.stdout.on('data', (data) => {
52
+ const CREDENTIALS = JSON.parse(data.toString());
53
+ const USERNAME = CREDENTIALS.user; // Get the RDS username from the credentials
54
+ const PASSWORD = CREDENTIALS.password; // Get the RDS password from the credentials
55
+
56
+ // Display connection credentials and connection string
57
+ console.log(`Your connection string is: psql -h localhost -p 5432 -U ${USERNAME} -d emr`);
58
+ console.log(`Use the password: ${PASSWORD}`);
59
+
60
+ // Get the ID of the bastion instance
61
+ const instanceIdCommand = `aws ec2 describe-instances --region us-east-2 --filters "Name=tag:Name,Values='*bastion*'" --query "Reservations[].Instances[].[InstanceId]" --output text`;
62
+ const instanceIdProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${instanceIdCommand}`]);
63
+
64
+ instanceIdProcess.stdout.on('data', (data) => {
65
+ const INSTANCE_ID = data.toString().trim();
66
+
67
+ if (!INSTANCE_ID) {
68
+ console.error('Failed to find the instance with tag Name=*bastion*.');
69
+ return;
70
+ }
71
+
72
+ // Get the endpoint of the RDS cluster
73
+ const rdsEndpointCommand = `aws rds describe-db-clusters --region us-east-2 --query "DBClusters[?contains(DBClusterIdentifier, 'rds-aurora')].Endpoint" --output text`;
74
+ const rdsEndpointProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${rdsEndpointCommand}`]);
75
+
76
+ rdsEndpointProcess.stdout.on('data', (data) => {
77
+ const RDS_ENDPOINT = data.toString().trim();
78
+
79
+ if (!RDS_ENDPOINT) {
80
+ console.error('Failed to find the RDS endpoint.');
81
+ return;
82
+ }
83
+
84
+ // Start a port forwarding session to the RDS cluster
85
+ const portForwardingCommand = `aws ssm start-session --target ${INSTANCE_ID} --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters "host=${RDS_ENDPOINT},portNumber='5432',localPortNumber='5432'" --cli-connect-timeout 0`;
86
+ const portForwardingProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${portForwardingCommand}`]);
87
+
88
+ portForwardingProcess.stdout.on('data', (data) => {
89
+ console.log(data.toString().trim());
90
+ });
91
+
92
+ portForwardingProcess.stderr.on('data', (data) => {
93
+ console.error(`Command execution error: ${data.toString()}`);
94
+ });
95
+ });
96
+
97
+ rdsEndpointProcess.stderr.on('data', (data) => {
98
+ console.error(`Command execution error: ${data.toString()}`);
99
+ });
100
+ });
101
+
102
+ instanceIdProcess.stderr.on('data', (data) => {
103
+ console.error(`Command execution error: ${data.toString()}`);
104
+ });
105
+ });
106
+
107
+ ssmGetProcess.stderr.on('data', (data) => {
108
+ console.error(`Command execution error: ${data.toString()}`);
109
+ });
110
+ });
111
+
112
+ ssmDescribeProcess.stderr.on('data', (data) => {
113
+ console.error(`Command execution error: ${data.toString()}`);
114
+ });
115
+ });
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "rds_ssm_connect",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "dependencies": {
6
+ "@aws-sdk/client-ec2": "^3.363.0",
7
+ "@aws-sdk/client-rds": "^3.363.0",
8
+ "@aws-sdk/client-ssm": "^3.363.0",
9
+ "aws-sdk": "^2.1411.0",
10
+ "inquirer": "^8.2.5",
11
+ "node-jq": "^2.3.5"
12
+ }
13
+ }