What's the best way to parse secret payload to a js plain object?

Viewed 363

I created a secret using the google cloud web UI. I import it directly from a .env file. Now I want to use them in a cloud function.

code here:

const { SecretManagerServiceClient } = require('@google-cloud/secret-manager');
const dotenv = require('dotenv');

const secretManagerServiceClient = new SecretManagerServiceClient();
const name = 'projects/<my_project_id>/secrets/workflow/versions/latest';

exports.testSecretManager = async (req, res) => {
  const [version] = await secretManagerServiceClient.accessSecretVersion({ name });
  const payload = version.payload.data.toString();
  console.debug(`Payload: ${payload}`);
  const buf = Buffer.from(payload);
  const secrets = dotenv.parse(buf);
  console.debug('secrets:', secrets);
  res.sendStatus(200);
};

version.payload.data.toString() will give me a raw string of .env file like this:

APP_PORT=3001
POSTGRES_HOST=db

I need to parse it to a js plain object so I can use it through object properties like payload.data.APP_PORT. For now, I use dotenv.parse to parse the raw string to a js plain object. The output like this:

{
  APP_PORT: 3001,
  POSTGRES_HOST: '127.0.0.1'
}

Is there a better way to do this? Does google secret manager or gcloud cli support create JSON format secret payload from a .env file? So I can use JSON.parse to parse the JSON string without using any third-party package?

0 Answers
Related