rds_ssm_connect 1.0.1 → 1.0.3

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.
@@ -0,0 +1,17 @@
1
+ name: Publish Package to npmjs
2
+ on:
3
+ release:
4
+ types: [published]
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ steps:
9
+ - uses: actions/checkout@v3
10
+ - uses: actions/setup-node@v3
11
+ with:
12
+ node-version: '18.x'
13
+ registry-url: 'https://registry.npmjs.org'
14
+ - run: npm ci
15
+ - run: npm publish
16
+ env:
17
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # AWS Environment Selector and Command Executor
2
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.
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 manage your AWS credentials securely.
4
4
 
5
5
  ## Prerequisites
6
6
 
@@ -10,16 +10,14 @@ Before running this application, make sure you have the following installed:
10
10
  - `aws-vault` tool: You can install it following the instructions on the [official GitHub page](https://github.com/99designs/aws-vault).
11
11
  - AWS CLI: You can install it following the instructions on the [official AWS page](https://aws.amazon.com/cli/).
12
12
 
13
- Also, ensure that your AWS configuration file (`~/.aws/config`) is properly set up with the environments you want to use.
13
+ Also, ensure that your AWS configuration file (`~/.aws/config`) is appropriately set up with the environments you want to use.
14
14
 
15
15
  ## Installation
16
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:
17
+ You can install this application globally using npm:
20
18
 
21
19
  ```bash
22
- npm install
20
+ npm install -g rds_ssm_connect
23
21
  ```
24
22
 
25
23
  ## Usage
@@ -27,7 +25,7 @@ npm install
27
25
  1. Run the application. It will read your AWS configuration file and prompt you to select an environment.
28
26
 
29
27
  ```bash
30
- node connect.js
28
+ rds_ssm_connect
31
29
  ```
32
30
 
33
31
  2. Select the environment you want to use. The application will then execute a series of AWS commands within that environment.
@@ -42,11 +40,7 @@ This application requires the following Node.js modules:
42
40
  - `os`: For getting the user's home directory.
43
41
  - `path`: For working with file paths.
44
42
 
45
- You can install these modules by running:
46
-
47
- ```bash
48
- npm install child_process inquirer fs os path
49
- ```
43
+ These modules will be installed automatically when you install the application with npm.
50
44
 
51
45
  ## How It Works
52
46
 
@@ -54,10 +48,11 @@ The application first reads the AWS configuration file and extracts the environm
54
48
 
55
49
  After the user selects an environment, the application executes a series of AWS commands within that environment using `aws-vault`. These commands include:
56
50
 
57
- - Describing SSM parameters to get the name of the parameter containing the RDS password.
51
+ - Describing SSM parameters to get the parameter's name containing the RDS password.
58
52
  - Getting the value of the RDS password parameter.
59
53
  - Describing EC2 instances to get the ID of the bastion instance.
60
54
  - Describing RDS DB clusters to get the endpoint of the RDS cluster.
61
55
  - Starting an AWS SSM session to forward a local port to the RDS cluster.
62
56
 
63
57
  The application logs the output of each command and any errors that occur.
58
+
package/connect.js CHANGED
@@ -16,102 +16,123 @@ const awsConfig = fs.readFileSync(awsConfigPath, 'utf-8');
16
16
  // Extract environments from AWS config file
17
17
  const ENVS = awsConfig
18
18
  .split('\n')
19
- .filter(line => line.startsWith('[') && line.endsWith(']'))
20
- .map(line => line.slice(1, -1))
21
- .map(line => line.replace('profile ', ''));
22
-
23
- // Prompt the user to select an environment
24
- inquirer
25
- .prompt([
26
- {
27
- type: 'list',
28
- name: 'ENV',
29
- message: 'Please select the environment:',
30
- choices: ENVS,
31
- },
32
- ])
33
- .then((answers) => {
34
- const ENV = answers.ENV; // Get the selected environment from the user's answers
35
- console.log(`You selected: ${ENV}`);
36
-
37
- // Set up the commands to run inside the aws-vault environment
38
- const awsVaultExecCommand = ['aws-vault', 'exec', ENV, '--'];
39
- 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';
40
-
41
- // Run the commands inside aws-vault environment
42
- const ssmDescribeProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmDescribeCommand}`]);
43
-
44
- // Get the name of the parameter containing the RDS password
45
- ssmDescribeProcess.stdout.on('data', (data) => {
46
- const PARAM_NAME = data.toString().trim();
47
-
48
- // Get the RDS credentials
49
- const ssmGetCommand = `aws ssm get-parameter --region us-east-2 --name '${PARAM_NAME}' --with-decryption --query Parameter.Value --output text`;
50
- const ssmGetProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmGetCommand}`]);
51
-
52
- // Parse the JSON output of the ssm get-parameter command to get the RDS credentials
53
- ssmGetProcess.stdout.on('data', (data) => {
54
- const CREDENTIALS = JSON.parse(data.toString());
55
- const USERNAME = CREDENTIALS.user; // Get the RDS username from the credentials
56
- const PASSWORD = CREDENTIALS.password; // Get the RDS password from the credentials
57
-
58
- // Display connection credentials and connection string
59
- console.log(`Your connection string is: psql -h localhost -p 5432 -U ${USERNAME} -d emr`);
60
- console.log(`Use the password: ${PASSWORD}`);
61
-
62
- // Get the ID of the bastion instance
63
- const instanceIdCommand = `aws ec2 describe-instances --region us-east-2 --filters "Name=tag:Name,Values='*bastion*'" --query "Reservations[].Instances[].[InstanceId]" --output text`;
64
- const instanceIdProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${instanceIdCommand}`]);
65
-
66
- instanceIdProcess.stdout.on('data', (data) => {
67
- const INSTANCE_ID = data.toString().trim();
68
-
69
- if (!INSTANCE_ID) {
70
- console.error('Failed to find the instance with tag Name=*bastion*.');
71
- return;
72
- }
73
-
74
- // Get the endpoint of the RDS cluster
75
- const rdsEndpointCommand = `aws rds describe-db-clusters --region us-east-2 --query "DBClusters[?contains(DBClusterIdentifier, 'rds-aurora')].Endpoint" --output text`;
76
- const rdsEndpointProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${rdsEndpointCommand}`]);
77
-
78
- rdsEndpointProcess.stdout.on('data', (data) => {
79
- const RDS_ENDPOINT = data.toString().trim();
80
-
81
- if (!RDS_ENDPOINT) {
82
- console.error('Failed to find the RDS endpoint.');
19
+ .filter(line => line.startsWith('[') && line.endsWith(']'))
20
+ .map(line => line.slice(1, -1))
21
+ .map(line => line.replace('profile ', ''));
22
+
23
+ // Define a mapping of environment suffixes to port numbers
24
+ const envPortMapping = {
25
+ 'dev': '5433',
26
+ 'stage': '5434',
27
+ 'pre-prod': '5435',
28
+ 'prod': '5436',
29
+ };
30
+
31
+ // Prompt the user to select an environment
32
+ inquirer
33
+ .prompt([
34
+ {
35
+ type: 'list',
36
+ name: 'ENV',
37
+ message: 'Please select the environment:',
38
+ choices: ENVS,
39
+ },
40
+ ])
41
+
42
+ .then((answers) => {
43
+ const ENV = answers.ENV; // Get the selected environment from the user's answers
44
+ console.log(`You selected: ${ENV}`);
45
+
46
+ // Extract the environment suffix from the selected environment
47
+ const envSuffix = ENV.split('-').pop();
48
+
49
+ // Get the corresponding port number for the environment
50
+ let portNumber = envPortMapping[envSuffix]; // Declare portNumber as a let variable
51
+
52
+ // If no port number is found for the environment, default to 5432
53
+ if (!portNumber) {
54
+ console.error(`No port number found for environment: ${ENV}. Defaulting to 5432.`);
55
+ portNumber = '5432';
56
+ }
57
+
58
+ // Set up the commands to run inside the aws-vault environment
59
+ const awsVaultExecCommand = ['aws-vault', 'exec', ENV, '--'];
60
+ 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';
61
+
62
+ // Run the commands inside aws-vault environment
63
+ const ssmDescribeProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmDescribeCommand}`]);
64
+
65
+ // Get the name of the parameter containing the RDS password
66
+ ssmDescribeProcess.stdout.on('data', (data) => {
67
+ const PARAM_NAME = data.toString().trim();
68
+
69
+ // Get the RDS credentials
70
+ const ssmGetCommand = `aws ssm get-parameter --region us-east-2 --name '${PARAM_NAME}' --with-decryption --query Parameter.Value --output text`;
71
+ const ssmGetProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${ssmGetCommand}`]);
72
+
73
+ // Parse the JSON output of the ssm get-parameter command to get the RDS credentials
74
+ ssmGetProcess.stdout.on('data', (data) => {
75
+ const CREDENTIALS = JSON.parse(data.toString());
76
+ const USERNAME = CREDENTIALS.user; // Get the RDS username from the credentials
77
+ const PASSWORD = CREDENTIALS.password; // Get the RDS password from the credentials
78
+
79
+ // Display connection credentials and connection string
80
+ console.log(`Your connection string is: psql -h localhost -p ${portNumber} -U ${USERNAME} -d emr`);
81
+ console.log(`Use the password: ${PASSWORD}`);
82
+
83
+ // Get the ID of the bastion instance
84
+ const instanceIdCommand = `aws ec2 describe-instances --region us-east-2 --filters "Name=tag:Name,Values='*bastion*'" --query "Reservations[].Instances[].[InstanceId]" --output text`;
85
+ const instanceIdProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${instanceIdCommand}`]);
86
+
87
+ instanceIdProcess.stdout.on('data', (data) => {
88
+ const INSTANCE_ID = data.toString().trim();
89
+
90
+ if (!INSTANCE_ID) {
91
+ console.error('Failed to find the instance with tag Name=*bastion*.');
83
92
  return;
84
93
  }
85
94
 
86
- // Start a port forwarding session to the RDS cluster
87
- 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`;
88
- const portForwardingProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${portForwardingCommand}`]);
95
+ // Get the endpoint of the RDS cluster
96
+ const rdsEndpointCommand = `aws rds describe-db-clusters --region us-east-2 --query "DBClusters[?contains(DBClusterIdentifier, 'rds-aurora')].Endpoint" --output text`;
97
+ const rdsEndpointProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${rdsEndpointCommand}`]);
89
98
 
90
- portForwardingProcess.stdout.on('data', (data) => {
91
- console.log(data.toString().trim());
99
+ rdsEndpointProcess.stdout.on('data', (data) => {
100
+ const RDS_ENDPOINT = data.toString().trim();
101
+
102
+ if (!RDS_ENDPOINT) {
103
+ console.error('Failed to find the RDS endpoint.');
104
+ return;
105
+ }
106
+
107
+ // Start a port forwarding session to the RDS cluster
108
+ const portForwardingCommand = `aws ssm start-session --target ${INSTANCE_ID} --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters "host=${RDS_ENDPOINT},portNumber='${portNumber}',localPortNumber='${portNumber}'" --cli-connect-timeout 0`;
109
+ const portForwardingProcess = spawn('sh', ['-c', `${awsVaultExecCommand.join(' ')} ${portForwardingCommand}`]);
110
+
111
+ portForwardingProcess.stdout.on('data', (data) => {
112
+ console.log(data.toString().trim());
113
+ });
114
+
115
+ portForwardingProcess.stderr.on('data', (data) => {
116
+ console.error(`Command execution error: ${data.toString()}`);
117
+ });
92
118
  });
93
119
 
94
- portForwardingProcess.stderr.on('data', (data) => {
120
+ rdsEndpointProcess.stderr.on('data', (data) => {
95
121
  console.error(`Command execution error: ${data.toString()}`);
96
122
  });
97
123
  });
98
124
 
99
- rdsEndpointProcess.stderr.on('data', (data) => {
125
+ instanceIdProcess.stderr.on('data', (data) => {
100
126
  console.error(`Command execution error: ${data.toString()}`);
101
127
  });
102
128
  });
103
129
 
104
- instanceIdProcess.stderr.on('data', (data) => {
130
+ ssmGetProcess.stderr.on('data', (data) => {
105
131
  console.error(`Command execution error: ${data.toString()}`);
106
132
  });
107
133
  });
108
134
 
109
- ssmGetProcess.stderr.on('data', (data) => {
135
+ ssmDescribeProcess.stderr.on('data', (data) => {
110
136
  console.error(`Command execution error: ${data.toString()}`);
111
137
  });
112
138
  });
113
-
114
- ssmDescribeProcess.stderr.on('data', (data) => {
115
- console.error(`Command execution error: ${data.toString()}`);
116
- });
117
- });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rds_ssm_connect",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "type": "module",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-ec2": "^3.363.0",