I'm very open to learning if there's a better "best practices" way to do this, but I have some scripts that I run occasionally that edit a database, and so I need to pass the DB password for those scripts. I'm getting the password by calling a function that calls google cloud Secrets Manager, and I'm unable to add it to the process.env.
for example if I put this at the top of my script file:
process.env.DB_HOST='127.0.0.1';
process.env.DB_USER='michael';
process.env.DB_NAME='staging-db';
process.env.DB_PORT=1234;
process.env.DB_PASS= await accessSecret('projects/myproject-123/secrets/DB_PASS/versions/latest');
When the above runs I get the error
SyntaxError: await is only valid in async functions and the top level bodies of modules
But, if I move the process.env.DB_PASS setting inside my async main() function, then it has local scope to that main function. Other files called by functions in this script see process.env.DB_PASS as undefined (but do see values for any process.env variables set globally at the top of the file.
How do I pull in and set that secret without actually pasting the literal secret into the code?
To represent the problem of the scoping, here's a working-code recreation of that problem in action. This is the script file I'm running:
process.env.DB_HOST='127.0.0.1';
process.env.DB_USER='michael';
process.env.DB_NAME='staging-db';
process.env.DB_PORT=1234;
const db = require('../../src/database/process_pull_test');
const main = async () => {
process.env.SCOPED_KEY = "helloimscoped"
db.hello();
}
main().catch((e) => {console.error(e)});
Here is the process_pull_test
file
console.log("SCOPED KEY", process.env.SCOPED_KEY);
const dbHost = process.env.DB_HOST;
const dbUser = process.env.DB_USER;
const dbName = process.env.DB_NAME;
const dbPort = process.env.DB_PORT;
const scopedKey = process.env.SCOPED_KEY;
async function hello() {
console.log(dbHost);
console.log(dbUser);
console.log(dbName);
console.log(dbPort);
console.log(scopedKey);
return console.log("Hello Secrets");
}
module.exports = {
hello: hello
}
And, here is the output
SCOPED KEY undefined
127.0.0.1
michael
staging-db
1234
undefined
Hello Secrets