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?
CodePudding user response:
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.
This is not correct, it will be set globally. Chances are simply that your other files execute before your main() runs.
Generally the solution is to simply make sure that after you set your environment variables in main(), you call all other logic. This means all your logic should be in functions.
CodePudding user response:
Typically you use some sort of configuration tool such as dotenv or config to manage app settings and secrets. Be sure NOT to save the secret files in source control.
