I also needed to read a secret from Secret Manager to avoid hardcoded value in Google App Script. After I had added a secret value in Secret Manager in GCP developer console, I enabled Secret Manager API.
And here is my solution:
First of all, open Project Settings menu in your App Script Editor (settings cogwheel icon on the panel to the left) and tick the checkbox:
"Show appsscript.json manifest file in editor"
This will make the appscript.json file visible in your project files near your main Code.gs.
Then add these lines into an existing dictionary in appscript.json:
"oauthScopes": [
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/cloud-platform"
]
This will enable the necessary scopes for your project.
I am reading API Key from Secret Manager, so I added getAPIKey() function in Code.gs:
function getAPIKey() {
let token, endpoint, response;
endpoint = `https://secretmanager.googleapis.com/v1/projects/<project_id>/secrets/<secret_name>/versions/<version_number>:access`;
token = ScriptApp.getOAuthToken();
response = UrlFetchApp.fetch(endpoint, {
headers: {
Authorization: 'Bearer ' + token,
Accept: 'application/json',
}
});
var decodedAPIKey = Utilities.base64Decode(JSON.parse(response.getContentText())['payload']['data']);
var apiKey = Utilities.newBlob(decodedAPIKey).getDataAsString()
return apiKey;
}
Google Cloud OAuth Token is used to authenticate this script to access Secret Manager. On the first run of the script, you will also need to do an authorization manually, but only once.
Please remember to add your project_id, secret_name and version_number. You will find this information in Secret Manager in Developer Console when open your secret value.
Then call this function in a place where you need your secret value.