I’m new to node/javascript and stuck on two main things:
- Pass multiple secret names with values from module to app.
- Using the secret names and values, create env vars for the app to use.
NodeJS version: v19.5.0
Everything on the GCP backend is configured and I don’t want to use .env files.
getSecrets.js
'use strict';
const secretsArray = [ 'SECRET_1', 'SECRET_2', 'SECRET_3' ]
const parent = 'projects/some-project';
// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
// Instantiates a client
const client = new SecretManagerServiceClient();
secretsArray.forEach((secret) => {
async function getSecret() {
const [version] = await client.accessSecretVersion({
name: `${parent}/secrets/${secret}/versions/latest`,
});
const payload = version.payload.data.toString();
console.log(`${secret} = ${payload}`);
}
getSecret();
});
This works by itself and returns three lines for each of the secrets:
SECRET_1 = randomString1
SECRET_2 = randomString2
SECRET_3 = randomString3
Tried wrapping the forEach loop in:
module.exports = () => {
return new Promise((resolve) => {
<forEach block>
});
}
with a new entry point: app.js
const express = require("express");
const cors = require("cors");
const getSecrets = require("./getSecrets");
const app = express();
app.use(cors());
app.listen(4000, async () => {
try {
console.log(await getSecrets());
} catch (error) {
console.log("Error in setting environment variables", error);
process.exit(-1);
}
});
When I run it, I only get one line for the last secret in the list:
SECRET_3 = randomString3
I’ve tried adding the values from each loop to a new array and sending that over, but it didn’t work for me. Or is there an entirely different approach that would be better?