How to Access Secrets from Google Secret Manager Using Apps Script

This detailed guide explains how to access your passwords, API keys and other sensitive data stored in Google Secret Manager with Google Apps Script.

Google Secret Manager is a cloud service where you can store sensitive data such as passwords, database credentials, encryption keys or any other confidential information that you don’t want to hardcode in your application’s source code. You can also set up an expiration time for the secret and Google Secret Manager will automatically delete the secret after the specified time.

The following guide explains how you can use Google Apps Script to access secrets stored in Google Secret Manager. But before we proceed, let’s first create a secret in Google Secret Manager.

Enable Google Privacy Manager

1. Open Google Cloud Console and create a new project.

2. Go to the Library section of your Google Cloud project and enable the Secret Manager API.

3. Go to the IAM and Admin > IAM section of your Google Cloud. Click on Grant Access and add Secret Manager Secret Accessor The Google Account role from which you want to access secrets stored in Google Secret Manager.

Create a secret in Google Secret Manager

Now that you’ve enabled the Secret Manager API and granted access to your Google Account, let’s create a new secret in Google Secret Manager.

Go to Secret Manager and click on Create Secret button to create a new secret.

Give your secret a name and add a secret value – this can be a plain text string, or you can upload a binary file up to 64KB in size. If you want the secret to expire after a certain time, you can set an expiration time for the secret.

In the above example, I have made the name secret MyBankPassword with price MySuperSecretPassword. Google Secret Manager will automatically assign a version number (1) to the secret. You cannot change the secret value once it is saved but you can create a new version of the secret with a different value.

Access Google Privacy Manager from Google Apps Script

Now that you’ve created a secret in Google Secret Manager, let’s write a Google Apps script that will retrieve the secret value from Google Secret Manager.

go to script.new To create a new Google Apps Script project. go to Project Settings and enable it Show appsscript.json manifest file in editor option. Switch to appsscript.json Open the tab and add the following OAuth scopes to the manifest file:

{
  "oauthScopes": (
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/cloud-platform"
  )
}

Next, add the following function to your Google Apps Script project. Replace it project_id, secret_idand version_id Variables with the actual values โ€‹โ€‹of your secret.

The project_id is the project number of your Google Cloud project and can be found here in the Google Cloud console.

After you’ve added the function to your Google Apps Script project, run main A function to fetch a secret value from Google Secret Manager and log it to Google Apps Script Logger.

const main = () => {
  const project_id = '<>';
  const secret_id = '<>';
  const secret_value = getSecretValue_({ project_id, secret_id });
  Logger.log('The secret value for %s is %s', secret_id, secret_value);
};

const getSecretValue_ = ({ project_id, secret_id, version_id = 1 }) => {
  const endpoint = `projects/${project_id}/secrets/${secret_id}/versions/${version_id}:access`;
  const api = `https://secretmanager.googleapis.com/v1/${endpoint}`;
  const response = UrlFetchApp.fetch(api, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
      'Content-Type': 'application/json',
    },
    muteHttpExceptions: true,
  });

  const { error, payload } = JSON.parse(response.getContentText());

  
  
  if (error) {
    throw new Error(error.message);
  }

  
  const bytes = Utilities.base64Decode(payload.data);
  const base64 = bytes.map((byte) => `%${byte.toString(16).padStart(2, '0')}`).join('');
  const secretValue = decodeURIComponent(base64);
  return secretValue;
};

Leave a Comment